iOS PDF文件的显示和浏览

本文介绍两种iOS平台上的PDF显示方法:一种使用UIWebView,简洁但不支持翻页;另一种使用CGContextDrawPDFPage配合UIScrollView实现缩放及UIPageViewController实现翻页效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简介

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

方法一:利用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。

UIScrollView

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

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

源码下载

PDFDemo

参考链接

http://blog.youkuaiyun.com/yiyaaixuexi/article/details/7645725

转载于:https://www.cnblogs.com/liyanyan/p/5442437.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值