在iOS中预览pdf文件,显示pdf的三种方式
1.WebView直接显示pdf文件
2.自定义UIView,运用CGPDFDocumentRef读取pdf文件内容,进行drawRect
3.使用Apple的文件预览控件:QLPreveiewController
自定义UIView的实现方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| #import "RiderPDFView.h"
@implementation RiderPDFView
- (void)drawRect:(CGRect)rect { NSString *pathStr = [[NSBundle mainBundle] pathForResource:@"my" ofType:@".pdf"]; CGPDFDocumentRef pdfRef = [self pdfRefByFilePath:pathStr];
CGContextRef context = UIGraphicsGetCurrentContext(); CGPDFPageRef pageRef = CGPDFDocumentGetPage(pdfRef, 1);//获取指定页的内容如catPage=1,获取的是pdf第一页的内容 CGRect mediaRect = CGPDFPageGetBoxRect(pageRef, kCGPDFCropBox);//pdf内容的rect
CGContextRetain(context); CGContextSaveGState(context);
[[UIColor whiteColor] set]; CGContextFillRect(context, rect);//填充背景色,否则为全黑色;
CGContextTranslateCTM(context, 0, rect.size.height);//设置位移,x,y;
CGFloat under_bar_height = 0.0f; CGContextScaleCTM(context, rect.size.width / mediaRect.size.width, -(rect.size.height + under_bar_height) / mediaRect.size.height);//缩放倍数--x轴和y轴
CGContextSetInterpolationQuality(context, kCGInterpolationHigh); CGContextSetRenderingIntent(context, kCGRenderingIntentDefault); CGContextDrawPDFPage(context, pageRef);//绘制pdf
CGContextRestoreGState(context); CGContextRelease(context); }
- (CGPDFDocumentRef)pdfRefByFilePath:(NSString *)aFilePath { CFStringRef path; CFURLRef url; CGPDFDocumentRef document;
path = CFStringCreateWithCString(NULL, [aFilePath UTF8String], kCFStringEncodingUTF8); url = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, NO); document = CGPDFDocumentCreateWithURL(url);
CFRelease(path); CFRelease(url);
return document; }
@end
|
调用
1 2
| RiderPDFView *view = [[RiderPDFView alloc]initWithFrame:CGRectMake(0, 60, self.view.frame.size.width, 300)]; [self.view addSubview:view];
|
参考资料
iOS–PDF