vue-pdf,不显示印章,不显示中文
记问题及修改过程
1、页面
<pdf v-for="item in pageTotal" :key="item" :src="pdfUrl" :page="item"></pdf>
2、引入
import pdf from 'vue-pdf'
import axios from "axios";
3、js
mounted() {
axios.get(this.$props.fileUrl, { responseType:"arraybuffer" }).then(res => {
this.pdfUrl = pdf.createLoadingTask({
// 将url PDF 转换为base64
url: this.arrayBufferToBase64(res.data),
// 引入外部字体解决中文及乱码问题
cMapUrl: 'https://unpkg.com/pdfjs-dist@2.0.943/cmaps/',
cMapPacked: true
})
// 多页pdf,查询页码
this.pdfUrl.promise.then(pdf => { this.pageTotal = pdf.numPages }).catch(() => {})
})
}
methods: {
// pdf转base64
arrayBufferToBase64(buffer) {
let binary = '';
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return 'data:application/pdf;base64,'+ window.btoa(binary);
}
},
注:
// CMapReaderFactory 和 cMapUrl 同时使用会造成冲突
import CMapReaderFactory from "vue-pdf/src/CMapReaderFactory";
到这里解决了一些中文不显示问题,印章问题还是存在,这里就涉及到插件源码问题
只需要注释掉:node_modules/pdfjs-dist//es5/build/pdf.worker.js/31691行
if (data.fieldType === "Sig") {
data.fieldValue = null;
// _this3.setFlags(_util.AnnotationFlag.HIDDEN);
}
但是只是本地包改掉了,在线上部署时还是会拉去新的包,所以这里用到了patch-package打补丁
npm i patch-package postinstall-postinstall -D
package.json中添加:
"scripts": {
"postinstall": "patch-package"
}
现在去修改node_modules下的文件,重新跑一遍,是否达到你想要的效果
运行:
npm patch-package vuejs-dist
这时会在根目录下生成patches/pdfjs-dist+2.6.347.patch文件
diff --git a/node_modules/pdfjs-dist/es5/build/pdf.worker.js b/node_modules/pdfjs-dist/es5/build/pdf.worker.js
index 578da90..4fd4ea0 100644
--- a/node_modules/pdfjs-dist/es5/build/pdf.worker.js
+++ b/node_modules/pdfjs-dist/es5/build/pdf.worker.js
@@ -31687,7 +31687,7 @@ var WidgetAnnotation = /*#__PURE__*/function (_Annotation2) {
if (data.fieldType === "Sig") {
data.fieldValue = null;
- _this3.setFlags(_util.AnnotationFlag.HIDDEN);
+ // _this3.setFlags(_util.AnnotationFlag.HIDDEN);
}
return _this3;
这里就是你修改的内容,线上打包时就会连同补丁一起打进去
测试可以将node_modules删掉,重新npm i,再次查看pdf.worker.js
最后:提代码,跑流水线,测试