pdf.js不分页渲染(渲染完整内容)

直接上代码
首先引入pdf.js 和 pdf.worker.js


// 渲染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();
        });
    });
}

看效果

pdf.js不分页渲染(渲染完整内容)_第1张图片
成功渲染所有分页 PS: 没有展示完全请检查_targetDom 这个标签节点是否拥有css属性 overflow-y: scroll;

页面有报错的请点我的另一篇文章查看

你可能感兴趣的:(pdf,javascript,前端)