Created
December 3, 2013 18:06
-
-
Save DougFischer/7774309 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| - (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