首页 技术 正文
技术 2022年11月12日
0 收藏 944 点赞 2,827 浏览 1845 个字

  事实上有很多种在前端展示PDF格式文档的方法,小编也用过好多种,例如有<iframe>、<embed>和<object>这些标签,但是在Vue项目里,这些方法都不能很好的展示PDF文档,实际上Vue给大家准备了展示PDF的插件,所以小编今天给大家讲解一下这个插件的用法。

  首先下载插件

    命令:npm install pdfjs-dist

  下载完毕以后新建一个组件用来存放PDF文档

  引入所需要的插件:

Vue之展示PDF格式的文档

  接下来就是Vue给大家已经准备好了展示PDF文档所需要的代码,不需要大家在手动书写了:

Vue之展示PDF格式的文档

  这里需要告诉大家,url最好还是传到七牛云上比较好(因为跨域这个东西很烦人)。

  下面给大家带来完整的代码:(这里要注意,存放PDF的容器最好用canvas)

<template>
<div>
<p>合同预览</p>
<canvas v-for="page in pages" :id="'the-canvas'+page" :key="page"></canvas>
</div>
</template><script>
import PDFJS from "pdfjs-dist";
import pdfjsLib from "pdfjs-dist";
// const Base64 = require('js-base64').Base64export default {
name: "ContractPreview",
data() {
return {
title: "查看协议",
pdfDoc: null,
pages: 0
};
},
methods: {
// 初始化pdfjs
initThePDFJSLIB: function() {
pdfjsLib.GlobalWorkerOptions.workerSrc = "pdfjs-dist/build/pdf.worker.js";
},
_renderPage(num) {
this.pdfDoc.getPage(num).then(page => {
let canvas = document.getElementById("the-canvas" + num);
let ctx = canvas.getContext("2d");
let dpr = window.devicePixelRatio || 1;
let bsr =
ctx.webkitBackingStorePixelRatio ||
ctx.mozBackingStorePixelRatio ||
ctx.msBackingStorePixelRatio ||
ctx.oBackingStorePixelRatio ||
ctx.backingStorePixelRatio ||
1;
let ratio = dpr / bsr;
let viewport = page.getViewport(
screen.availWidth / page.getViewport(1).width
);
canvas.width = viewport.width * ratio;
canvas.height = viewport.height * ratio;
canvas.style.width = viewport.width + "px";
canvas.style.height = viewport.height + "px";
ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
let renderContext = {
canvasContext: ctx,
viewport: viewport
};
page.render(renderContext);
if (this.pages > num) {
this._renderPage(num + 1);
}
});
},
_loadFile(url) {
PDFJS.getDocument(url).then(pdf => {
this.pdfDoc = pdf;
this.pages = this.pdfDoc.numPages;
this.$nextTick(() => {
this._renderPage(1);
});
});
}
},
mounted() {
this.initThePDFJSLIB();
document.title = this.title;
let url = 'PDF链接地址’;
console.log(url);
this._loadFile(url);
}
};
</script><style scoped>
canvas {
display: block;
border-bottom: 1px solid black;
}
</style>
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,999
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,511
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,357
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,140
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,770
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,848