I am developing an application which render a PDF file using CoreGraphics. I am displaying one page of the PDF at a time. In viewDidLoad I have the following code:
NSString *pdfFullPath = [[NSBundle mainBundle] pathForResource:@"catalogue" ofType:@"pdf"];
pdf = CGPDFDocumentCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:pdfFullPath]);
currentPage = [[_dataObject description] intValue];
[pdfView setImage:[self imageFromPDF:pdf withPageNumber:currentPage withScale:1.5]];
[_dataObject description] contains the current page number as a string.
Then I have this method which renders the PDF:
- (UIImage *)imageFromPDF:(CGPDFDocumentRef)_pdf withPageNumber:(NSUInteger)pageNumber withScale:(CGFloat)scale
{
if(pageNumber > 0 && pageNumber <= CGPDFDocumentGetNumberOfPages(_pdf))
{
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(_pdf, pageNumber);
CGRect tmpRect = CGPDFPageGetBoxRect(pdfPage,kCGPDFMediaBox);
CGRect rect = CGRectMake(tmpRect.origin.x, tmpRect.origin.y, tmpRect.size.width * scale, tmpRect.size.height * scale);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0, rect.size.height);
CGContextScaleCTM(context, scale, -scale);
CGContextDrawPDFPage(context, pdfPage);
UIImage *pdfImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return pdfImage;
}
return nil;
}
This seems to be a very slow process which locks the application entirely when imageFromPDF is being called and therefore I am looking for any way to optimize the process so it would be faster. Any ideas?
What I ended up doing is to save each page of the PDF as an image on the iPad. The name of the images is the page number. When I flip to a new page I check if the file exists on the iPad. E.g. for page 4 I would check if “4.jpg” exists, if it does, I will show “4.jpg” else I will render the page and save it.
This approach might use a lot of space on the iPad but for my use that’s not really an issue as the application will not end up on App Store but will be used for salesmen in a company.