前端pdf操作

14 篇文章 0 订阅

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可以自己定
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值