我正在尝试使用CGPDFDocumentRef将PDF的单页转换为图像。但是,这仅适用于某些PDF而不适用于其他PDF(例如,它适用于this PDF但不适用于this one)。有什么区别?
我的PDF转换代码:
-(UIImage *)pdfToImg: (NSURL *)pdfURL {
// create CGPDF from URL
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
// get reference to page
CGPDFPageRef page1 = CGPDFDocumentGetPage(pdf, 1); // page 1
// get size of page
CGRect pageRect = CGPDFPageGetBoxRect(page1, kCGPDFMediaBox);
CGSize pageSize = pageRect.size;
// edit DPI
float dpi = 300.0 / 72.0; // change numerator to increase or decrease dpi
pageSize.width = pageSize.width * dpi;
pageSize.height = pageSize.height * dpi;
// ---conversion process---
UIGraphicsBeginImageContext(pageSize);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGContextTranslateCTM(context, 0.0, pageSize.height);
CGContextScaleCTM(context, dpi, -dpi);
CGContextSaveGState(context);
//CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(pdfPageRef, kCGPDFCropBox, CGRectMake(0, 0, pageSize.width, pageSize.height), 0, true);
//CGContextConcatCTM(context, pdfTransform);
CGContextDrawPDFPage(context, page1);
CGContextRestoreGState(context);
// ------
// create image
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultingImage;
}
提前谢谢!