March 21, 2018

iOS端查看PDF文档实现方案

文 · Mark

在不同端查看一些文档时,往往会展现出千奇百怪的格式,呈现给用户的也是不同的展示效果。为了保持原始文稿的格式,保证展现效果的统一,PDF文稿可以很好解决格式在不同端文稿展现格式差异,保持原始文稿的展现效果。

对于移动端的开发工作中,查看PDF也是常见的需求,本文针对iOS端查看PDF文档给出实现方案,包括通过网络端读取和本地读取两种方式查看PDF文档。

读取方式

  • 网络读取
  • 本地读取

测试文稿样本

实现方式

经过调研,目前针对网络读取,可以使用UIWebView进行PDF文档加载及展示;针对本地PDF文档读取,可以通过QLPreviewController进行读取并展示。

UIWebView展现

本方法用于在线展示云端PDF文档;

关键代码如下:

self.webViewPDFViewer = [[UIWebView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_AND_STATUS_BAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT-NAVIGATION_BAR_AND_STATUS_BAR_HEIGHT)];
self.webViewPDFViewer.delegate = self;
[self.view addSubview:self.webViewPDFViewer];

// Load the PDF document online
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:PDF_FILE_URL]];
[self.webViewPDFViewer loadRequest:urlRequest];

展现截图:

注意

  • 通过WebView加载网络端过程中会有等待情况,建议增加Loading提示

QLPreviewController展现

该方式可查看多种文件类型,主要适用于本地文件读取展示,包括:

  • iWork documents
  • Microsoft Office documents (Office ‘97 and newer)
  • Rich Text Format (RTF) documents
  • PDF files
  • Images
  • Text files whose uniform type identifier (UTI) conforms to the public.text type (see Uniform Type Identifiers Reference)
  • Comma-separated value (csv) files

关键代码

/*!
 * @abstract Returns the item that the preview controller should preview.
 * @param panel The Preview Controller.
 * @param index The index of the item to preview.
 * @result An item conforming to the QLPreviewItem protocol.
 */
- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
    NSString *pdfFilePath = [[NSBundle mainBundle] pathForResource:@"Accessory-Design-Guidelines" ofType:@"pdf"];
    return [NSURL fileURLWithPath:pdfFilePath];
}

注意

在iOS11.2 系统上,查看云端PDF文档会出现如下错误:

... : [default] Couldn't issue file extension for url: https://developer.apple.com/accessories/Accessory-Design-Guidelines.pdf #PreviewItem

相关链接及解决方法

若使用该方法查看PDF文档,建议先将文件进行下载,保存到App的Document某一目录,再进行文件展示。

PDFKit展现

该方式是iOS11.0 SDK添加,支持PDF文件读取和写入。

考虑到此API版本需要的系统版本较高,本文暂不调研,后续会进行专门补充。