最近做了一个需求–在html页面展示PDF文档 遇到的问题:在浏览器上可以用iframe正常打开pdf文件。但是当html嵌套在手机app里面的时候,-iframe嵌套的PDF文件就不能正常展示了。
解决办法: 1.尝试过使用安卓方法进行文件下载之后,打开PDF文件(这个方法只能在新页面打开PDF文件),但我需要在原有的页面进行PDF文档显示。 2.优化–pdf转图片显示,满足当前页面参考文档,且转为图片后暂时没有模糊等其他问题(采用)
pdf-dist使用步骤
1、下载pdf-dist包,放在public文件下面,在页面中引用方法使用(https://gitee.com/mirrors/pdfjs-dist/) 2、安装pdf-dist(npm i pdf-dist) 3、在对应的页面中引用pdf-dist
import * as PDFJS from "pdfjs-dist";
4、初始化pdf插件
readPdf(fileUrl) {
let self = this
self.pdfPicturePath = []
const loadingTask = PDFJS.getDocument(fileUrl);
loadingTask.promise.then(function (pdf) {
if (pdf) {
const pageNum = pdf.numPages;
for (let i = 1; i <= pageNum; i++) {
const canvas = document.createElement('canvas');
canvas.id = "pageNum" + i;
(self.$refs as any).docView.append(canvas);
const context = canvas.getContext('2d');
self.openPage(pdf, i, context);
}
setTimeout(() => {
self.exportImg(self)
}, 1000);
}
}).catch(function (reason) {
console.error("Error: " + reason);
});
}
5、pdf转成canvas
openPage(pdfFile, pageNumber, context) {
let scale = 2;
let that = this
pdfFile.getPage(pageNumber).then(function (page) {
const viewport = page.getViewport(scale);
let canvas = context.canvas;
canvas.width = viewport.width;
canvas.height = viewport.height;
canvas.style.width = "100%";
canvas.style.height = "100%";
let renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
that.loading = false
});
return;
}
6、canvas转成图片(可根据具体情况,进行图片转化显示) 这里我把所有图片的base64存放在数组里面,方便放大查看,也可以直接把生成图片标签进行图片展示
exportImg(self) {
let canvaslist: any = document.querySelectorAll('canvas');
for (let i = 0; i < canvaslist.length; i++) {
let canvasNode = document.getElementById("pageNum" + (i + 1));
this.pdfPicturePath.push((canvasNode as any).toDataURL("image/png"))
}
}
踩坑
1、控制台报GlobalWorkerOptions of undefined
'GlobalWorkerOptions' of undefined
解决方法:下载指定版本的pdf-dist依赖,pdf-dist@2.2.228(测试有效)
2、GlobalWorkerOptions.workerSrc of undefined 解决办法: 1、找到node_modules>_pdfjs-dist@2.2.228@pdfjs-dist>build>pdf.js文件,把GlobalWorkerOprions.workerSrc的undefined更改为./pdf.worker.js的路径 2、页面中更改
import * as pdfjsLib from 'pdfjs-dist'
import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry'
初始化PDF插件方法里面加上这个,手动赋值workerSrc 地址
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker;
- 参考文章地址:https://www.cnblogs.com/wx1993/p/12533899.html
- 参考文章地址:https://blog.csdn.net/JaneLittle/article/details/107033764
|