I’ve found some code which gives me a UIImage out of a PDF-File. It works, but I have two questions:
- Is there a possibility to achieve a better quality of the UIImage? (See Screenshot)
- I only see the first page in my
UIImageView. Do I have to embed the file in aUIScrollViewto be complete? - Or is it better to render just one page and use buttons to navigate through the pages?
P.S. I know that UIWebView can display PDF-Pages with some functionalities but I need it as a UIImage or at least in a UIView.
Bad quality Image:

Code:
-(UIImage *)image {
UIGraphicsBeginImageContext(CGSizeMake(280, 320));
CGContextRef context = UIGraphicsGetCurrentContext();
CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("ls.pdf"), NULL, NULL);
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
CGContextTranslateCTM(context, 0.0, 320);
CGContextScaleCTM(context, 1.0, -1.0);
CGPDFPageRef page = CGPDFDocumentGetPage(pdf, 4);
CGContextSaveGState(context);
CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFCropBox, CGRectMake(0, 0, 280, 320), 0, true);
CGContextConcatCTM(context, pdfTransform);
CGContextDrawPDFPage(context, page);
CGContextRestoreGState(context);
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultingImage;
}
What are you doing with the
CGContextTranslateCTM(context, 0.0, 320);call?You should extract the proper metrics form the pdf, with code like this:
Also, as you see, the pdf might has rotation info, so you need to use the
CGContextTranslateCTM/CGContextRotateCTM/CGContextScaleCTMdepending on the angle.You also might wanna clip any content that is outside of the
CropBoxarea, as pdf has variousviewPortsthat you usually don’t wanna display (e.g. for printers so that seamless printing is possible) -> useCGContextClip.Next, you’re forgetting that the pdf reference defines a white background color. There are a lot of documents out there that don’t define any background color at all – you’ll get weird results if you don’t draw a white background on your own –>
CGContextSetRGBFillColor&CGContextFillRect.