错误类型:
> npm install pdfjs-dist
>引入 解决#docId = 0;问题,用下面的方法引入,不要用mdn。在VUE或react或其他页面引入然后使用全局变量即可。会存在window下。
var PDFJS = require("pdfjs-dist/legacy/build/pdf.js");
import workerSrc from "pdfjs-dist/legacy/build/pdf.worker.entry";
PDFJS.GlobalWorkerOptions.workerSrc = workerSrc;
console.log("开始 pDF测试");
console.log(workerSrc);
console.log(PDFJS);
console.log("结束");
>JS vue案例
this.$nextTick(() => {
const loadingTask = (this.loadingTask = PDFJS.getDocument({
url: url,
cMapUrl: "./cmaps/",//必须引入字体文件
// cMapUrl: 'https://cdn.jsdelivr.net/npm/pdfjs-dist@2.0.288/cmaps/',
cMapPacked: true,
}));
// this._initParams(loadingTask);//自定义的方法
});
async _initParams(loadingTask) {
this.pdf = await loadingTask.promise;
const { numPages } = this.pdf;
this.totalPage = this.numPages = numPages;
// this.setPageNum();//渲染逻辑自行定义
},
OK完事,剩下的就是canvas渲染了。看文档地址。火狐官方标准核心库,争当copy少年:Examples
>补丁:鱿鱼没错,鱿鱼官方的坑。没有补全,中国人不骗中国人的原则,发布补丁:
我提了,没人理我,他们说只兼容主流的就可以了。看不起谁呢。自己加吧。
>第一个BUG:入口html顶部加入
<script>
this.globalThis || (this.globalThis = this);
</script>
>第二个BUG:>正则表达式正确,改为 "^(\\s)|(\\p{Mn})|(\\p{Cf})$/u" 原来的是("^(\\s)|(\\p{Mn})|(\\p{Cf})$",“u”)
//修改 pdf.worker 源码
//修改 pdf.worker 源码
const SpecialCharRegExp = new RegExp("^(\\s)|(\\p{Mn})|(\\p{Cf})$/u");
>第三个八嘎:
//修改 pdf.js源码在顶部加上兼容代码。中国人加,歪果人不要加。火狐官方最新标准的不需要。
if (!String.prototype.padStart) {
String.prototype.padStart = function padStart(targetLength, padString) {
targetLength = targetLength >> 0; //floor if number or convert non-number to 0;
padString = String(typeof padString !== 'undefined' ? padString : ' ');
if (this.length > targetLength) {
return String(this);
} else {
targetLength = targetLength - this.length;
if (targetLength > padString.length) {
padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
}
return padString.slice(0, targetLength) + String(this);
}
};
}
### 另一种解决办法
安装固定版本为 :
"pdfjs-dist": "2.5.207",
直接再JS中引入并使用模块
var PDFJS = require("pdfjs-dist/es5/build/pdf.js");
import workerSrc from "pdfjs-dist/es5/build/pdf.worker.entry";
PDFJS.GlobalWorkerOptions.workerSrc = workerSrc;
函数中设置以下初始化,需要将字体文件带入到当前目录下,可以去官网或者node_modules里面复制 过来:
const loadingTask = (this.loadingTask = PDFJS.getDocument({
url: url,
cMapUrl: "./cmaps/",
// cMapUrl: 'https://cdn.jsdelivr.net/npm/pdfjs-dist@2.0.288/cmaps/',
cMapPacked: true,
}));
本文只提供解决版本问题:至于业务功能,大家根据自己的需求去定义。