简体   繁体   English

在 Canvas PDF JS 中渲染 PDF

[英]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.我正在尝试在滚动时一一呈现 pdf 中的页面,就像在 PDF JS 演示中一样。 I am using PDF JS.我正在使用 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.所以基本上这个想法是像PDF Js的演示一样更快地加载pdf。

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:

<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.但至于为什么 pdf 可能渲染缓慢,可能是 pdf 的大小,pdf 中有很多内容或许多其他内容。 You could also try the cdn instead of including the build files:您也可以尝试使用 cdn 而不是包含构建文件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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