简体   繁体   中英

PDF Rendering in Canvas PDF JS

I am trying to render pages in a pdf one by one upon scroll as they have in the demo of PDF JS. I am using PDF JS. i have rendered all the pages at once, but that is taking some time to load all the pages. So basically the idea is to load the pdf faster as in the demo of PDF Js.

I have shared the code below where i have rendered all the pages at once but that is taking a little more time than expected.

HTML:

<html>
    <head>
        <title>PDF JS Demo</title>
        <style>
            #holder {
                width: 100%;
                height: 500px;
                overflow: auto;
                background: #333;
                text-align: center;
                border: 1px solid;
                margin-bottom: 25px;
            }
            canvas {
                margin-bottom: 15px;
            }
        </style>
    </head>
<body>

<script src="build/pdf.js"></script>
<script src="build/pdf.worker.js"></script>
<script type="text/javascript" src="build/simple.js"></script>

<div id="holder"></div>

<script type="text/javascript">
reUsableRenderPDF('build/HygieneReport_New.pdf', document.getElementById('holder'));
</script>
</body>
</html>

JAVASCRIPT:




function reUsableRenderPDF(url, canvasContainer, options) {

    var options = options || { zoom: 1.0 };

    function renderPage(page) {
        var viewport = page.getViewport(options.zoom);
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        var renderContext = {
          canvasContext: ctx,
          viewport: viewport
        };

        canvas.height = viewport.height;
        canvas.width = viewport.width;

        canvasContainer.appendChild(canvas);

        page.render(renderContext);
    }

    function renderPages(pdfDoc) {
        for(var num = 1; num <= pdfDoc.numPages; num++)
            pdfDoc.getPage(num).then(renderPage);
    }

    pdfjsLib.disableWorker = true;
    pdfjsLib.getDocument(url).then(renderPages);

}   

您应该只渲染多页 pdf,而不是一次渲染所有 pdf 页面,也就是说您在第 5 页,您可以渲染第 3 4 和 6 7 页,但要做到这一点,您需要知道当前页面的位置您可以获取接近当前页码的页面并渲染它们,但是当您滚动到不同的页面时,您需要从 HTML 中删除旧的渲染。

you didn't really ask a specific question. But as to why the pdf may be rendering slowly it could be the size of the pdf, there being a lot of content within the pdf or a number of other things. You could also try the cdn instead of including the build files:

<script src="https://cdn.jsdelivr.net/npm/pdfjs-dist@2.1.266/build/pdf.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM