WKWebView接入PDF.js過程記錄處理總結

問題

最近用WKWebView讀取PDF文件出現字體異常、電子圖章不顯示的問題,後來查找很多解決方案,最後決定用PDF.js的方式來實現

解決方案

  1. 參考https://www.jianshu.com/p/ded81b392d4d 寫了demo能接入PDF,但部分字體在真機上還是接入異常,後來使用
gulp generic-legacy

生成generic-legacy穩定包之後,對Safari進行兼容後,終於能修復字體異常的問題

  1. 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 */
}
  1. 讀取本地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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章