Skip to content

Instantly share code, notes, and snippets.

@larsacus
Created November 14, 2011 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save larsacus/1365108 to your computer and use it in GitHub Desktop.
Save larsacus/1365108 to your computer and use it in GitHub Desktop.
Render PDF document to UIImage
NSString *pdfPath = [[NSBundle mainBundle] pathForResource:@"pdf_name" ofType:@"pdf"];//this is assuming the pdf is in the main bundle
NSInteger pageNumber = 1;//for a one-page PDF
CGSize containerSize = self.imageView.bounds.size;
UIGraphicsBeginImageContext(containerSize);
CGContextRef context = UIGraphicsGetCurrentContext();
const char *pdfFileName = [pdfPath cStringUsingEncoding:NSASCIIStringEncoding];
CGDataProviderRef pdfDataProvider = CGDataProviderCreateWithFilename(pdfFileName);
CGPDFDocumentRef myDocument = CGPDFDocumentCreateWithProvider(pdfDataProvider);
CFRelease(pdfDataProvider);
CGPDFPageRef page = CGPDFDocumentGetPage(myDocument, pageNumber);
CGContextTranslateCTM(context, 0.0, self.imageView.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFCropBox, self.imageView.frame, 0,true);
CGContextConcatCTM(context, pdfTransform);
CGContextDrawPDFPage(context, page);
CFRelease(myDocument);
CGImageRef imageRef = CGBitmapContextCreateImage(context);
UIImage *pdfImage = [UIImage imageWithCGImage:imageRef];
CFRelease(imageRef);
UIGraphicsEndImageContext();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment