如何使用pdf.js库呈现整个pdf文档?

时间:2014-08-06 14:07:28

标签: javascript pdf.js pdfview pdf-rendering

我尝试使用pdf.js库渲染PDF文档。我只知道javascript中的基础知识并且我是承诺的新手,所以最初我在这个页面上遵循了建议:Render .pdf to single Canvas using pdf.js and ImageData(2。回答)。
但结果,我把所有页面都空白了。所有的图片和颜色都很好,但甚至不是一行文字。我也尝试了其他一些教程,但要么得到相同的结果,要么文档完全丢失。 现在,我的代码看起来像这样:(它与教程几乎相同)

function loadPDFJS(pid, pageUrl){

    PDFJS.disableWorker = true;
    PDFJS.workerSrc = 'pdfjs/build/pdf.worker.js';

    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    var pages = [];
    var currentPage = 1;

    var url = '/search/nimg/IMG_FULL/' + pid + '#page=1';

    PDFJS.getDocument(url).then(function (pdf) {

        if(currentPage <= pdf.numPages) getPage();

        function getPage() {
            pdf.getPage(currentPage).then(function(page){
                var scale = 1.5;
                var viewport = page.getViewport(scale);

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

                var renderContext = {
                    canvasContext: ctx,
                    viewport: viewport
                };

                page.render(renderContext).then(function() {
                    pages.push(canvas.toDataURL());
                    if(currentPage < pdf.numPages) {
                        currentPage++;
                        getPage();
                    } else {
                        done();
                    }
                });
            });
        }
    });

    function done() {
        for(var i = 0; i < pages.length; i++){
            drawPage(i, addPage);
        }
    }

    function addPage(img){
        document.body.appendChild(img);
    }

    function drawPage(index, callback){
        var img = new Image;
        img.onload = function() {
            ctx.drawImage(this, 0, 0, ctx.canvas.width, ctx.canvas.height);
            callback(this);
        }
        img.src = pages[index];
    }
}

4 个答案:

答案 0 :(得分:5)

谢谢@ user3913960,你的概念对我有用。我在你修复的代码中发现了一些问题。这是代码:

function loadPDFJS(pageUrl) {
    PDFJS.workerSrc = 'resources/js/pdfjs/pdf.worker.js';
    var currentPage = 1;
    var pages = [];
    var globalPdf = null;
    var container = document.getElementById('pdf-container');
    function renderPage(page) {
        //
        // Prepare canvas using PDF page dimensions
        //
        var canvas = document.createElement('canvas');
        // Link: http://stackoverflow.com/a/13039183/1577396
        // Canvas width should be set to the window's width for appropriate
        // scaling factor of the document with respect to the canvas width
        var viewport = page.getViewport(window.screen.width / page.getViewport(1.0).width);
        // append the created canvas to the container
        container.appendChild(canvas);
        // Get context of the canvas
        var context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        //
        // Render PDF page into canvas context
        //
        var renderContext = {
            canvasContext: context,
            viewport: viewport
        };
        page.render(renderContext).then(function () {
            if (currentPage < globalPdf.numPages) {
                pages[currentPage] = canvas;
                currentPage++;
                globalPdf.getPage(currentPage).then(renderPage);
            } else {
                // Callback function here, which will trigger when all pages are loaded
            }
        });
    }
    PDFJS.getDocument(pageUrl).then(function (pdf) {
        if(!globalPdf){
            globalPdf = pdf;
        }
        pdf.getPage(currentPage).then(renderPage);
    });
}
loadPDFJS("somepdffilenamehere.pdf");

答案 1 :(得分:3)

K所以我再次查看了我的代码,我开始了。我让它更简单,我终于让它工作了。现在它看起来像这样:

var canvasContainer = document.getElementById('pdfImageImg');
function loadPDFJS(pid, pageUrl){

    PDFJS.workerSrc = 'pdfjs/build/pdf.worker.js';

    var currentPage = 1;
    var pages = [];
    var url = '/search/nimg/IMG_FULL/' + pid + '#page=1';

    PDFJS.getDocument(url).then(function(pdf) {
            pdf.getPage(currentPage).then(renderPage);

    function renderPage(page) {
        var height = 700;
        var viewport = page.getViewport(1);
        var scale = height / viewport.height;
        var scaledViewport = page.getViewport(scale);

        var canvas = document.createElement('canvas');
        var context = canvas.getContext('2d');
        canvas.height = scaledViewport.height;
        canvas.width = scaledViewport.width;

        var renderContext = {
            canvasContext: context,
            viewport: scaledViewport
        };
        page.render(renderContext).then(function () {
            if(currentPage < pdf.numPages) {
                pages[currentPage] = canvas;
                currentPage++;
                pdf.getPage(currentPage).then(renderPage);
            } else {
                for (var i = 1; i < pages.length; i++) {
                    document.getElementById('pdfImageImg').appendChild(pages[i]);
                }
            }
        });
    }

    });
}

答案 2 :(得分:2)

pdfjs-dist库包含用于构建PDF查看器的部件。您可以使用PDFPageView呈现所有页面。基于https://github.com/mozilla/pdf.js/blob/master/examples/components/pageviewer.html

&#13;
&#13;
var url = "https://cdn.mozilla.net/pdfjs/tracemonkey.pdf";
var container = document.getElementById('container');
// Load document
PDFJS.getDocument(url).then(function (doc) {
  var promise = Promise.resolve();
  for (var i = 0; i < doc.numPages; i++) {
    // One-by-one load pages
    promise = promise.then(function (id) {
      return doc.getPage(id + 1).then(function (pdfPage) {
// Add div with page view.
var SCALE = 1.0; 
var pdfPageView = new PDFJS.PDFPageView({
      container: container,
      id: id,
      scale: SCALE,
      defaultViewport: pdfPage.getViewport(SCALE),
      // We can enable text/annotations layers, if needed
      textLayerFactory: new PDFJS.DefaultTextLayerFactory(),
      annotationLayerFactory: new PDFJS.DefaultAnnotationLayerFactory()
    });
    // Associates the actual page with the view, and drawing it
    pdfPageView.setPdfPage(pdfPage);
    return pdfPageView.draw();        
      });
    }.bind(null, i));
  }
  return promise;
});
&#13;
#container > *:not(:first-child) {
  border-top: solid 1px black; 
}
&#13;
<link href="https://npmcdn.com/pdfjs-dist/web/pdf_viewer.css" rel="stylesheet"/>
<script src="https://npmcdn.com/pdfjs-dist/web/compatibility.js"></script>
<script src="https://npmcdn.com/pdfjs-dist/build/pdf.js"></script>
<script src="https://npmcdn.com/pdfjs-dist/web/pdf_viewer.js"></script>

<div id="container" class="pdfViewer singlePageView"></div>
&#13;
&#13;
&#13;

另见How to display whole PDF (not only one page) with PDF.JS?

答案 3 :(得分:0)

我使用下面的代码来渲染包含多个页面的pdf。

pStr