iOS在路上iOS

iOS使用pdf.js打开PDF文件

2017-05-12  本文已影响4076人  雪小影

最近研究了下iOS打开PDF文件的方式,由于项目需要在浏览PDF文件时能使用HTML格式文件,调研了一下iOS中打开PDF文件的几种方式,发现pdf.js开源库可以做到这一点,通过调用js在线预览PDF文件,预览时将PDF文件转为HTML标签,而且集成方便。

pdf.js是火狐浏览器的开源项目,github地址为:https://github.com/mozilla/pdf.js

教程中把pdf.js作为服务端的步骤:

$ git clone git://github.com/mozilla/pdf.js.git
$ cd pdf.js
$ npm install --global gulp-cli
$ npm install -g gulp-cli
$ npm install
$ gulp server

将pdf.js集成到iOS工程中的步骤:

$ gulp generic
$ gulp minified
 - (void)loadPDFFile:(NSString*)filePath {
    _filePath = filePath;
  
    NSString *viwerPath = [[NSBundle mainBundle] pathForResource:@"viewer" ofType:@"html" inDirectory:@"minified/web"];
    NSString *urlStr = [NSString stringWithFormat:@"%@?file=%@#page=1",viwerPath,filePath];
    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    [self loadRequest:request];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    PDFWebView *webView = [[PDFWebView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:webView];
    NSString *pdfFilePath = [[NSBundle mainBundle] pathForResource:@"git搭建" ofType:@"pdf"];
    [webView loadPDFFile:pdfFilePath];
}

参考资料

上一篇下一篇

猜你喜欢

热点阅读