通过使用 UIWebView 渲染 pdf,我们将无法正确控制 pdf。就像我们不能直接转到所需的页面。而且我们无法搜索特定的单词并突出显示。
最好使用 CGPDFDocumentRef 和 CGPDFPageRef 等 CGPDF 类来正确处理 pdf 文档。
使用这些类,我们有两个选项来处理 pdf。
1.将pdf页面单独提取为图像并使用UIImageView显示。
2.使用CGPDFPageRef提取每个页面的内容,并在运行时为每个页面创建pdf并显示到webview上。(更好地控制pdf和整洁的显示)
以下是将单个页面提取为图像的示例代码。
-(UIImage *)getPage : (NSString*) filePath{
const char *myBuffer = (const char*)filePath; // PDF Path
CFStringRef urlString = (CFStringRef)myBuffer;
CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, urlString, 2, NO);
CGPDFDocumentRef myDocumentRef = CGPDFDocumentCreateWithURL(url);
CGPDFPageRef myPageRef = CGPDFDocumentGetPage(myDocumentRef, 1);
CGRect pdfcropBox = CGPDFPageGetBoxRect(myPageRef,kCGPDFCropBox); //kCGPDFCropBox
UIGraphicsBeginImageContext (pdfcropBox.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM (context,0,pdfcropBox.size.height);// [self pageRect].origin.x,[self pageRect].origin.y+[self pageRect].size.height); //320);
// scale 1:1 100%
CGContextScaleCTM (context, 1.0, -1.0);
CGContextSaveGState (context);
CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(myPageRef, kCGPDFCropBox, CGRectMake(0, 0, pdfcropBox.size.width,pdfcropBox.size.height), 0, true); //
CGContextConcatCTM (context, pdfTransform);
CGContextDrawPDFPage (context, myPageRef);
CGContextRestoreGState (context);
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext ();
CGPDFDocumentRelease (myDocumentRef);
//CGPDFPageRelease(myPageRef);
//myPageRef = nil;
myDocumentRef = nil;
urlString = nil;
url = nil;
return resultingImage;
}