h5 pdf预览
Packjson: 使用cnpm 下载pdfjs-dist
"pdfjs-dist": "^2.4.456",
html:
<div v-if="PDF_IMG_List.length>0">
<img
style="width:100%;height:100%;"
v-for="(item,index) in PDF_IMG_List"
:key="index"
:src="item"
/>
</div>
js部分:
import PDFJS from "pdfjs-dist";
PDFJS.GlobalWorkerOptions.workerSrc =
"https://cdn.bootcdn.net/ajax/libs/pdf.js/2.4.456/pdf.worker.min.js";
data:{
Return{
PDF_IMG_List: [],
PDF_Obj: null,
PDFTotalPage:0
}
}
PDFJS.getDocument(url).promise.then(async res => {
//url'为pdf地址
this.PDF_Obj = res; //pdf下载成功
this.PDFTotalPage = res.numPages; //总页数
for (let i = 1; i <= this.PDFTotalPage; i++) {
const page = await res.getPage(i);
let viewport = page.getViewport({ scale: 1 });
this.$refs.cvs.width = viewport.width;
this.$refs.cvs.height = viewport.height;
await page.render({
canvasContext: this.$refs.cvs.getContext("2d"),
viewport
}).promise;
this.PDF_IMG_List.push(this.$refs.cvs.toDataURL("image/png", 1));
}
});
这篇博客介绍了如何利用PDFJS库在前端实现PDF文档的预览,并将每一页转换为图片。首先通过cnpm安装pdfjs-dist,然后在HTML中展示图片列表。在JavaScript中,获取PDF文档总页数,遍历每一页,将其渲染到canvas并转化为PNG图片数据,存储在PDF_IMG_List数组中。
428

被折叠的 条评论
为什么被折叠?



