- iOS下加載PDF,不管是UIWebView還是WKWebView都可以輕松做到,再不行可以使用UIDocumentInteractionController;
- 安卓的webView無法直接預覽PDF,安卓一般都是用
PDFJS插件,前端頁面也是用這個插件,我們公司有個APP所有詳情都是PDF格式的,為了多端界面統(tǒng)一,我也采用PDFJS插件
一、引入PDFJS
直接去mozilla/pdfjs-dist下載,這里也有一份弄好的 ??傳送門
解壓后項目中引入時,必須保證目錄結構不變(PDFJS內(nèi)部有資源互相引用,不能打亂),所以一定要選擇Create folder refrences

image.png
二、基于UIWebView使用PDFJS
可以看出,其實使用這個插件的方法就是拿到
viewer .html,然后添加url參數(shù)file,值就是我們PDF文件的路徑
/// 使用本地PDFJS加載PDF
- (void)openPDF:(NSString *)pdfPath {
NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"viewer" ofType:@"html" inDirectory:@"minified/web"];
NSString *urlStr = [NSString stringWithFormat:@"%@?file=%@#page=1",htmlPath,pdfPath];
urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
[self.webView loadRequest:request];
}
三、基于WKWebView使用PDFJS
- 由于UIWebView太老了 (其實用起來很方便,操作簡單,我也一直沒有把WKWebView用起來),并且明年貌似使用UIWebView控件項目無法上架,所以....
- 把UIWebView替換成WKWebView發(fā)現(xiàn)加載不了PDF了,原因是WKWebView訪問本地文件有一些權限問題
那應該如何加載PDFJS框架呢?
可以開啟一個HTTP服務,通過http來加載相關資源,這里要啟用一個庫CocoaHttpServer,使用它來搭建一個本地的web服務(具體參考示例 )
導入相關庫

image.png
示例代碼
#import "ViewController.h"
#import "HTTPServer.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
#import <WebKit/WebKit.h>
// Log levels: off, error, warn, info, verbose
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
@interface ViewController ()
{
HTTPServer *httpServer;
}
@property (strong, nonatomic) IBOutlet WKWebView *webView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self startServer];
// 加載本地PDF
NSString *pdfPath = [[NSBundle mainBundle] pathForResource:@"demo.pdf" ofType:nil];
[self openPDF:pdfPath];
}
/// 使用本地PDFJS加載PDF
- (void)openPDF:(NSString *)pdfPath {
NSString *urlStr = [NSString stringWithFormat:@"http://127.0.0.1/minified/web/viewer.html?file=/demo.pdf#page=1"];
urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
[self.webView loadRequest:request];
}
- (void)startServer
{
// 開啟打印日志
[DDLog addLogger:[DDTTYLogger sharedInstance]];
httpServer = [[HTTPServer alloc] init];
[httpServer setType:@"_http._tcp."];
// 設置端口
[httpServer setPort:80];
// 設置web根路徑
NSString *webPath = [[NSBundle mainBundle] resourcePath];
[httpServer setDocumentRoot:webPath];
// 開啟web服務
NSError *error;
if ([httpServer start:&error])
{
DDLogInfo(@"Started HTTP Server on port %hu", [httpServer listeningPort]);
}else {
DDLogError(@"Error starting HTTP Server: %@", error);
}
}
@end