pdf.js使用详解
项目中需要用到PDF的在线预览技术,自己百度摸索了很久终于搞出来了。记录一下
1、首先肯定是 npm i pdfjs-dist 下来,然后全局或者局部引入
注意 :这里就是重点了,必须对请求的请求头加上这么一句
responseType: 'arraybuffer' 这很关键,会让后端返回的数据默认为buffer数组,然后就可以用pdf.js官方文档上的方法进行canvas渲染了,下面上代码
请求的配置
return http({
method: 'GET',
url: url,
responseType: 'arraybuffer'
})
具体操作代码 (着色部分为获取到正确的buffer数组后传入该方法即可在页面上渲染PDF)
<template>
<div id="docdetailword">
<div id="canvasBox">
<p v-if="shownodata">暂无数据</p>
</div>
</div>
</template>
<script>
import api from "@/assets/api"
import mdContract from '@/components/contract.md.vue'
import PDFJS from "pdfjs-dist";
PDFJS.GlobalWorkerOptions.workerSrc = 'pdfjs-dist/build/pdf.worker.js';
export default {
name: 'docdetailword',
data () {
return {
shownodata : false
}
},
created () {
this.checkSuccess(); //获取文书PDF
},
methods:{
checkSuccess() {
api.getdocpdf(`/umale-cases-web/docs/pdf/case/${this.$store.docbasedetail.case_num}/doc/${this.$store.docbasedetail.id}`)// /umale-cases-web/docs/pdf/case/7d946bbe729c47d399c2a0537d1a4bc1/doc/1986
.then( res => {
if(res.data.byteLength === 0) {
this.shownodata = true
}else{
this.pdfToCanvas(res.data);
}
})
},
/**
* 将 pdf 绘制到 canvas
*/
pdfToCanvas(pdfArrayBuffer) {
return new Promise(async (resolve, reject) => {
const pdfData = await PDFJS.getDocument(pdfArrayBuffer);
const fragment = document.createDocumentFragment();
const canvasBox = document.querySelector("#canvasBox");
const numPages = pdfData.numPages;
for (let i = 1; i <= numPages; i++) {
let canvas = document.createElement("canvas");
let scale = 1;
let page = await pdfData.getPage(i);
let viewport = page.getViewport(scale); // reference canvas via context
canvas.id = "pageNum" + i;
canvas.width = viewport.width;
canvas.height = viewport.height;
canvas.style.width = "100%";
canvas.style.height = "100%";
let renderContext = {
canvasContext: canvas.getContext("2d"),
viewport: viewport
};
page.render(renderContext);
fragment.appendChild(canvas);
}
canvasBox.appendChild(fragment);
setTimeout(() => {
resolve(); //防止 canvas 没有绘制完
}, 5000);
});
},
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
#canvasBox{
width: 100%;
height: 100%;
text-align: center;
p{
margin-top: 200px;
color: #ACACAC;
}
}
</style>