iOS PDF文件的显示和浏览

简介

这里介绍两种方法显示PDF,第一种用UIWebView,特色是代码简单,可是无法实现翻页效果。第二中方法利用IOS系统的CGContextDrawPDFPage方法手动实现,代码复杂一些,同时须要配合UIScrollView实现缩放,以及利用UIPageViewController实现翻页的效果。git

方法一:利用UIWebView

1
2 3 4 5 6 
-(void)loadPDF:(NSString*)fileName inWebView:(UIWebView*)webView{  NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];  NSURL *url = [NSURL fileURLWithPath:path];  NSURLRequest *request = [NSURLRequest requestWithURL:url];  [webView loadRequest:request]; } 
  • 技巧:设置webView.scalesPageToFit = YES;能够实现pinch放大缩小
  • 缺点:没有翻页的动画效果

方法二:利用CGContextDrawPDFPage

CGContextDrawPDFPage

1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 
-(void)drawInContext:(CGContextRef)context atPageNo:(int)page_no{  // PDF page drawing expects a Lower-Left coordinate system, so we flip the coordinate system  // before we start drawing.  CGContextTranslateCTM(context, 0.0, self.bounds.size.height);  CGContextScaleCTM(context, 1.0, -1.0);   if (pageNO == 0) {  pageNO = 1;  }  CGPDFPageRef page = CGPDFDocumentGetPage(pdfDocument, pageNO);  CGContextSaveGState(context);  {  CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFCropBox, self.bounds, 0, true);  CGContextConcatCTM(context, pdfTransform);  CGContextDrawPDFPage(context, page);  }  CGContextRestoreGState(context); } 

须要先反转坐标,根据pageNO获取到CGPDFDocumentRef的那一页,直接CGContextDrawPDFPage。github

UIScrollView

配合UIScrollView实现缩放,ZPDFPageController的主要代码:web

1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 
-(void)viewDidLoad{  [super viewDidLoad];  UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];  scrollView.showsVerticalScrollIndicator=NO;  scrollView.showsHorizontalScrollIndicator=NO;  scrollView.minimumZoomScale=1.0f;  scrollView.maximumZoomScale=3.0f;  scrollView.delegate=self;  [self.view addSubview:scrollView];   pdfView = [[ZPDFView alloc] initWithFrame:scrollView.bounds atPage:(int)self.pageNO withPDFDoc:self.pdfDocument];  pdfView.backgroundColor=[UIColor whiteColor];  [scrollView addSubview:pdfView];   scrollView.contentSize=pdfView.bounds.size; }  - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{  return pdfView; } 

UIPageViewController

UIPageViewController的TransitionStyle设置为UIPageViewControllerTransitionStylePageCurl(翻页)。其次也是构建UIPageViewControllerDataSource中的两个方法(ZPDFPageModel)。要注意他们返回的是UIViewController,具体实现请参考源码。动画

效果展现

PDF1 PDF2

源码下载

PDFDemourl

参考连接

http://blog.csdn.net/yiyaaixuexi/article/details/7645725spa

相关文章
相关标签/搜索