问题
最近用WKWebView读取PDF文件出现字体异常、电子图章不显示的问题,后来查找很多解决方案,最后决定用PDF.js的方式来实现
解决方案
- 参考https://www.jianshu.com/p/ded81b392d4d 写了demo能接入PDF,但部分字体在真机上还是接入异常,后来使用
gulp generic-legacy
生成generic-legacy稳定包之后,对Safari进行兼容后,终于能修复字体异常的问题
- PDF.js自带顶部工具类功能,如果想要去掉,只能通过修改viewer.css来实现,添加如下代码
div.toolbar {
display: none;
}
#outerContainer #mainContainer div.toolbar {
display: none !important; /* hide PDF viewer toolbar */
opacity: 0.5 !important;
}
#outerContainer #mainContainer #viewerContainer {
top: 0 !important; /* move doc up into empty bar space */
}
- 读取本地PDF文件的方式有两个,一个是初始化接入参数,一个是通过bytes方式动态加载读取
初始化接入参数:
NSString *viwerPath = [[NSBundle mainBundle] pathForResource:@"viewer" ofType:@"html" inDirectory:@"generic/web"];
NSString *urlStr = [NSString stringWithFormat:@"file://%@?file=%@#page=1",viwerPath,filePath];
urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
[self loadRequest:request];
bytes方式动态加载读取:
SBundle mainBundle] pathForResource:@"viewer" ofType:@"html" inDirectory:@"generic/web"];
NSURL * viwerPathURL = [NSURL fileURLWithPath:viwerPath];
NSURL * dir = viwerPathURL.URLByDeletingLastPathComponent;
[self loadFileURL:viwerPathURL allowingReadAccessToURL:dir];
//动态加载的写法
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSData *data = [NSData dataWithContentsOfURL:filePath];
NSUInteger len = [data length];
uint8_t myArray[len];
[data getBytes:&myArray length:len];
NSMutableArray<NSString *> *bytes = [NSMutableArray array];
const uint8_t *rawBytes = data.bytes;
for (NSUInteger i = 0; i < data.length; i++) {
[bytes addObject:[NSString stringWithFormat:@"%d", (int)rawBytes[i]]];
}
NSString *javaScriptArray = [bytes componentsJoinedByString:@","];
NSString *strForEvaluate = [NSString stringWithFormat:
@"PDFViewerApplication.open(new Uint8Array([%@]));", javaScriptArray];
[self evaluateJavaScript:strForEvaluate completionHandler:^(id Result, NSError * _Nullable error) {
if (error)
{
NSLog(@"This is error....%@",error.description);
}
else if(Result)
{
NSLog(@"+++%@",Result);
}
}];
});
demo地址:https://github.com/freesan44/PDFJSReader
参考:
https://github.com/mozilla/pdf.js
https://www.jianshu.com/p/fd5f248a8158
https://www.jianshu.com/p/ded81b392d4d
https://github.com/mozilla/pdf.js/issues/2784