解决安卓端WebView预览 pdf 慢的问题
背景
安卓端的邻小汇预览pdf文件非常慢,甚至打不开
主要原因
- 使用的是 github 提供的地址 https://mozilla.github.io/pdf.js/web/viewer.html
- 服务器在外网,不稳定,访问慢甚至打不开
解决办法
将服务部署在自己的服务器上
1. 获取项目编译代码
- 下载已编译好的文件 https://mozilla.github.io/pdf.js/
- 不需要考虑安装依赖问题,比如 node@12
- 下载原项目,自行编译 https://github.com/mozilla/pdf.js
- 取自通过
gulp generic
打包后的build/generic/build/
目录下的文件 - 可以修改配置,比如 运行跨域
- 编译后的文件路径为 build/generic
- 取自通过
file origin does not match
,注释掉以下代码
如果遇到跨域问题 web/app.js 或 build/generic/web/viewer.js
// const fileOrigin = new URL(file, window.location.href).origin;
// Removing of the following line will not guarantee that the viewer will
// start accepting URLs from foreign origin -- CORS headers on the remote
// server must be properly configured.
// if (fileOrigin !== viewerOrigin) {
// throw new Error("file origin does not match viewer's");
// }
2. 部署
将文件夹(build、web )放进需要部署的项目内
- 特定的工程项目(不推荐)
- 需要占用15MB大小,增加项目体积
- 其他项目需要使用时
- 如果再次进行部署,重复部署,浪费资源
- 如果使用已经部署的项目地址,会存在依赖的问题,比如 项目路径变动、项目挂掉、项目维护等,会导致无法正常使用
- 公共的服务项目,这里使用 静态资源管理项目(推荐)
- https://gitlab.lanhanba.com/front-end-web/staticres
- 添加进项目内的 libs/preview-pdf 文件夹下
3. 使用方式
https://staticres.linhuiba.com/libs/preview-pdf/web/viewer.html?file=url
其中,url 是预览文件的地址,如 https://cert.linhuiba.com/FiYupA3Kyv5h2KqGLCNF7dGL7IEh
适用范围
其他端、其他项目的 webview 也可以使用