This is the first PDF class I have made for the iOS using code from Apple's samples. There could easily be stuff here wrong that I am missing.
I intend this to get images out of for a layer, for example:
image.contents = (id)[self.test imageForPage: 3 size: CGSizeMake(4*dpc, 2*dpc)].CGImage;
Here is this hopefully decent code. Any suggestions are welcome.
@interface PDFDocument : NSObject {
CGPDFDocumentRef pdfFile;
}
- (id) initWithURL: (NSURL*) url;
- (UIImage*) imageForPage: (size_t) pageno size: (CGSize) size;
- (CGSize) sizeOfPage: (size_t) pageno;
@end
@implementation PDFDocument
- (id) initWithURL: (NSURL*) url {
if ([super init])
{
// Open PDF
CGPDFDocumentRef doc = CGPDFDocumentCreateWithURL((CFURLRef)url);
if (doc == NULL)
@throw @"PDF File does not exist.";
pdfFile = doc;
}
return self;
}
- (UIImage*) imageForPage: (size_t) pageno size: (CGSize) size {
if (pdfFile) {
// Get First Page
CGPDFPageRef page = CGPDFDocumentGetPage(pdfFile, pageno);
if (page == NULL)
@throw @"Page does not exist.";
// Get Page Size
CGRect cropBox = CGPDFPageGetBoxRect(page, kCGPDFCropBox);
// Start Drawing Context to Render PDF
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0);
CGRect u = { {0, 0}, size};
CGContextFillRect(context, u);
CGContextSetAllowsAntialiasing(context, NO);
CGContextSaveGState(context);
// Scale PDF
CGContextScaleCTM(context, size.width / cropBox.size.width, size.height / cropBox.size.height);
// Flip Context to render PDF correctly
CGContextTranslateCTM(context, 0.0, cropBox.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawPDFPage(context, page);
CGContextRestoreGState(context);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); // must retain?
UIGraphicsEndImageContext();
return img;
}
return nil;
}
- (CGSize) sizeOfPage: (size_t) pageno {
if (pdfFile) {
CGPDFPageRef page = CGPDFDocumentGetPage(pdfFile, pageno);
if (page == NULL)
@throw @"Page does not exist";
CGRect cropBox = CGPDFPageGetBoxRect(page, kCGPDFCropBox);
return cropBox.size;
}
@throw @"No document loaded.";
}
@end