最近用WKWebView读取PDF文件出现字体异常、电子图章不显示的问题,后来查找很多解决方案,最后决定用PDF.js的方式来实现
gulp generic-legacy
生成generic-legacy稳定包之后,对Safari进行兼容后,终于能修复字体异常的问题
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 */
}
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