vue-pdf 对pdf.js进行了二次封装。为了适应项目,做了如下改动
在pdfjs包中找到es5/pdf.worker.js
在pdf.worker.js 中,注释掉 _this3.setFlags(_util.AnnotationFlag.HIDDEN) 可以让电子签章显示。
在vue-pdf中,使用canvas渲染pdf文件页面。微信中不支持下载pdf文件,而且canvas也无法另存为图片。这里采用增加img标签的方法,让canvas渲染的我图片再次渲染到img标签中。这样就可以在微信中下载pdf图片了
改动如下,在vue-pdf中找到componentFactory.js文件,并在render中修改虚拟dom的结构。
render: function(h) {
return h('span', {
attrs: {
style: 'position: relative; display: block'
}
}, [
h('canvas', {
style:{
'position': 'absolute',
'z-index': 1,
'display': 'inline-block',
"width": "100%",
"height": "100%",
"vertical-align": "top"
},
ref:'canvas'
}),
//增加图片显示
h('img',{
style: {
'width':"100%",
'position': "absolute",
'z-index': 100,
},
ref:"img"
}),
h('span', {
style: 'display: inline-block; width: 100%; height: 100%',
class: 'annotationLayer',
ref:'annotationLayer'
}),
h(resizeSensor, {
props: {
initial: true
},
on: {
resize: this.resize
},
})
])
其实就是增加了img标签。
然后在loadPage的时候,延时渲染img标签
watch: {
page: function() {
this.pdf.loadPage(this.page, this.rotate);
setTimeout(()=>{
this.$refs.img.src = this.$refs.canvas.toDataURL("image/png")
},500)
}
}
同样的,在mounted中,也要同样增加渲染
mounted: function() {
this.pdf = new PDFJSWrapper(this.$refs.canvas, this.$refs.annotationLayer, this.$emit.bind(this));
this.$on('loaded', function() {
this.pdf.loadPage(this.page, this.rotate);
//就是这段
setTimeout(()=>{
this.$refs.img.src = this.$refs.canvas.toDataURL("image/png")
},500)
});
this.$on('page-size', function(width, height) {
this.$refs.canvas.style.height = this.$refs.canvas.offsetWidth * (height / width) + 'px';
});
this.pdf.loadDocument(this.src);
},
这样就可以在微信中显示处图片,并将其另存为图片。
将canvas中的文件另存为pdf的方法如下,使用file-saver保存文件
import { saveAs } from "file-saver";
//
download(){
const self = this;
var bstr = atob(self.resData);//这里self.resData为base64的字符串,不带"data:application/pdf;base64,"如果有,要去掉
var n = bstr.length;
var u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
var blob = new Blob([u8arr], { type: "application/pdf" });
saveAs(blob, self.title || "download" + ".pdf");//这个title可以自己定
}