直接上代码
首先引入pdf.js 和 pdf.worker.js
javascript
// 渲染pdf
const pdfUrl = 'test1.pdf', _targetDom = 'pdf-container';
pdfjsLib.getDocument(pdfUrl).promise.then(async doc => {
let _i = 0;
for (let item of new Array(doc.numPages).fill()) {
await renderOtherPage(doc, ++_i, _targetDom)
};
});
// 渲染PDF视图
function renderOtherPage(pdfDoc, pageNumber) {
return new Promise(resolve => {
pdfDoc.getPage(pageNumber).then(page => {
const scale = 1.5;
const viewport = page.getViewport({ scale: scale });
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
document.getElementById(_targetDom).appendChild(canvas);
const renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
resolve();
});
});
}
看效果
成功渲染所有分页 PS: 没有展示完全请检查_targetDom 这个标签节点是否拥有css属性 overflow-y: scroll;
页面有报错的请点我的另一篇文章查看