Skip to content

Instantly share code, notes, and snippets.

@mayoff
Created August 12, 2013 22:58
Show Gist options
  • Save mayoff/6216140 to your computer and use it in GitHub Desktop.
Save mayoff/6216140 to your computer and use it in GitHub Desktop.
A UIImage category that renders one page of a PDF.
#import <UIKit/UIKit.h>
@interface UIImage (Rob_PDFPage)
/**
I return an image in which I have drawn page `pageNumber` of the PDF found at `url`. Pages are numbered starting at 1. If I can't draw the page, I return `nil`.
*/
+ (UIImage *)Rob_imageWithPDFURL:(NSURL *)url pageNumber:(size_t)pageNumber;
@end
#import "UIImage+Rob_PDFPage.h"
@implementation UIImage (Rob_PDFPage)
+ (UIImage *)Rob_imageWithSize:(CGSize)size opaque:(BOOL)opaque scale:(CGFloat)scale block:(void (^)(CGContextRef gc))block {
UIGraphicsBeginImageContextWithOptions(size, opaque, scale);
block(UIGraphicsGetCurrentContext());
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
+ (UIImage *)Rob_imageWithPDFPage:(CGPDFPageRef)page {
if (!page)
return nil;
CGRect box = CGPDFPageGetBoxRect(page, kCGPDFTrimBox);
return [self Rob_imageWithSize:box.size opaque:NO scale:0 block:^(CGContextRef gc) {
CGContextTranslateCTM(gc, 0, box.size.height);
CGContextScaleCTM(gc, 1, -1);
CGContextTranslateCTM(gc, -box.origin.x, -box.origin.y);
CGContextDrawPDFPage(gc, page);
}];
}
+ (UIImage *)Rob_imageWithPDFURL:(NSURL *)url pageNumber:(size_t)pageNumber {
CGPDFDocumentRef document = CGPDFDocumentCreateWithURL((__bridge CFURLRef)(url));
if (!document)
return nil;
UIImage *image = [self Rob_imageWithPDFPage:CGPDFDocumentGetPage(document, pageNumber)];
CGPDFDocumentRelease(document);
return image;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment