Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A UIImage category to create images from PDF files, useful for resolution independent UI elements.
// Copyright Harry Jordan, 2012 http://inquisitivesoftware.com/
// Open source under the MIT license http://www.opensource.org/licenses/MIT
#import <UIKit/UIKit.h>
#import <CoreGraphics/CoreGraphics.h>
@interface UIImage (AJKImageWithPDF)
+ (UIImage *)imageWithPDFNamed:(NSString *)pdfName;
+ (UIImage *)imageWithPDFNamed:(NSString *)pdfName scale:(CGFloat)scale;
@end
// Copyright Harry Jordan, 2012 http://inquisitivesoftware.com/
// Open source under the MIT license http://www.opensource.org/licenses/MIT
#import "UIImage+WithPDF.h"
@implementation UIImage (AJKImageWithPDF)
+ (UIImage *)imageWithPDFNamed:(NSString *)pdfName
{
return [UIImage imageWithPDFNamed:pdfName scale:0];
}
+ (UIImage *)imageWithPDFNamed:(NSString *)pdfName scale:(CGFloat)scale
{
if(!pdfName || [pdfName length] == 0)
return nil;
NSURL *imageURL = [[NSBundle mainBundle] URLForResource:pdfName withExtension:@"pdf"];
if(!imageURL) {
NSLog(@"Couldn't find a PDF document named: %@", pdfName);
return nil;
}
// Load the pdf
CGPDFDocumentRef pdfDocument = CGPDFDocumentCreateWithURL((__bridge CFURLRef)imageURL);
if(!pdfDocument) {
NSLog(@"Couldn't load the PDF document named: %@", pdfName);
return nil;
}
CGPDFPageRef firstPage = CGPDFDocumentGetPage(pdfDocument, 1);
if(!firstPage) {
NSLog(@"Couldn't find any pages for the PDF document named: %@", pdfName);
CGPDFDocumentRelease(pdfDocument);
return nil;
}
CGSize imageSize = CGPDFPageGetBoxRect(firstPage, kCGPDFCropBox).size;
// Scale the image by the
if(scale < 0.00001f)
scale = [[UIScreen mainScreen] scale];
imageSize.width *= scale;
imageSize.height *= scale;
// Setup a graphics context to draw into
UIGraphicsBeginImageContext(imageSize);
CGContextRef context = UIGraphicsGetCurrentContext();
// Flip the context so that the image draws the right way up
CGContextTranslateCTM(context, 0, imageSize.height);
CGContextScaleCTM(context, scale, -scale);
// Draw the pdf into the context
CGContextDrawPDFPage(context, firstPage);
// Create an image from the context
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGPDFDocumentRelease(pdfDocument);
return image;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment