注意事项:
1:安卓端下载只需要一个a标签,但是对应的url是pdf的地址(后端返回,相对路径那个),不是base64那个地址;
2:苹果端pdf转换成图片展示,并长按保存处理,pdfjs-dist要用指定版本,单独下载 npm i pdfjs-dist@2.4.456 -D
以上细节很重要
pdf展示处理(安卓):
图片展示处理(苹果):
loadTestCanvas() {
const url = this.pdfUrl; //pdf地址
let loadingTask = PDFJS.getDocument(url); //url的方式,下面介绍base64方式
loadingTask.promise.then(pdf => {
this.pdfDoc = pdf;
this.pdf_pages = 1; // this.pdfDoc.numPages;
this.$nextTick(() => {
//这边pdf就一页,默认为1页
this._renderPage(1);
});
});
},
_renderPage(num) {
//渲染pdf页
const that = this;
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({ scale: 1 }); //缩放默认为1
canvas.width = viewport.width * ratio;
canvas.height = viewport.height * ratio;
canvas.style.width = '100vw';
canvas.style.height = '0px';
ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
let renderContext = {
canvasContext: ctx,
viewport: viewport
};
// page.render(renderContext);
const renderTask = page.render(renderContext);
renderTask.promise.then(() => {
const imgUrl = canvas.toDataURL('image/jpeg');
this.imgUrl = imgUrl;
console.log(this.imgUrl);
console.log('===============')
});
});
},
html代码: