Skip to content

Instantly share code, notes, and snippets.

@DougFischer
Created December 3, 2013 18:06
Show Gist options
  • Select an option

  • Save DougFischer/7774309 to your computer and use it in GitHub Desktop.

Select an option

Save DougFischer/7774309 to your computer and use it in GitHub Desktop.
- (id)init {
self = [super init];
if (self) {
loadedThumbnails = [[NSCache alloc] init];
[loadedThumbnails setCountLimit:10];
}
return self;
}
- (UIImage *)thumbnailForPDFOfPath:(NSString *)path {
//Try get from NSCache
UIImage *thumbnail = [loadedThumbnails objectForKey:path];
//If not find
if (!thumbnail) {
//Create
NSURL *pdfFileUrl = [NSURL fileURLWithPath:path];
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((__bridge CFURLRef)pdfFileUrl);
CGPDFPageRef page = CGPDFDocumentGetPage(pdf, 1);//for the first page
CGRect aRect = CGPDFPageGetBoxRect(page, kCGPDFCropBox);
UIGraphicsBeginImageContext(aRect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0.0, aRect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextTranslateCTM(context, -(aRect.origin.x), -(aRect.origin.y));
CGContextSetGrayFillColor(context, 1.0, 1.0);
CGContextFillRect(context, aRect);
CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFCropBox, aRect, 0, false);
CGContextConcatCTM(context, pdfTransform);
CGContextDrawPDFPage(context, page);
thumbnail = UIGraphicsGetImageFromCurrentImageContext();
CGContextRestoreGState(context);
UIGraphicsEndImageContext();
CGPDFDocumentRelease(pdf);
//Store on cache
if (thumbnail && path) {
[loadedThumbnails setObject:thumbnail forKey:path];
}
}
return thumbnail;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment