How to render whole pdf document using pdf.js library?

后端 未结 4 560
一生所求
一生所求 2020-12-29 14:24

I tried rendering PDF document using pdf.js library. I know only basics in javascript and I am new to promises, so at first I followed advice on this page: Render .pdf to si

相关标签:
4条回答
  • 2020-12-29 14:44

    K so I just looked at my code again and I started all over. I made it simpler and I finally got it to work. Now it looks like this:

    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]);
                    }
                }
            });
        }
    
        });
    }
    
    0 讨论(0)
  • 2020-12-29 14:50

    The pdfjs-dist library contains parts for building PDF viewer. You can use PDFPageView to render all pages. Based on https://github.com/mozilla/pdf.js/blob/master/examples/components/pageviewer.html :

    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;
    });
    #container > *:not(:first-child) {
      border-top: solid 1px black; 
    }
    <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>

    See also How to display whole PDF (not only one page) with PDF.JS?

    0 讨论(0)
  • 2020-12-29 14:52

    I have used below code to render a pdf with multiple pages.

    PDFJS.disableWorker = true; // due to CORS
    var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d'),
    pages = [],
    currentPage = 1,
    url = 'your_pdf.pdf';
    
    PDFJS.getDocument(url).then(function(pdf) {
      if (currentPage <= pdf.numPages) getPage();
    
      // main entry point/function for loop
      function getPage() {
        // when promise is returned do as usual
        pdf.getPage(currentPage).then(function(page) {
          var scale = 1;
          var viewport = page.getViewport(scale);
          canvas.height = viewport.height;
          canvas.width = viewport.width;
    
          var renderContext = {
            canvasContext: ctx,
            viewport: viewport
          };
    
          // now, tap into the returned promise from render:
          page.render(renderContext).then(function() {
            // store compressed image data in array
            pages.push(canvas.toDataURL());
    
            if (currentPage < pdf.numPages) {
              currentPage++;
              getPage(); // get next page
            } else {
              // after all the pages are parsed
              for (var i = 0; i < pages.length; i++) {
                drawPage(i);
              }
            }
          });
        });
      }
    });
    
    function drawPage(index, callback) {
      var img = new Image;
      img.onload = function() {
        ctx.drawImage(this, 0, 0, ctx.canvas.width, ctx.canvas.height);
        if (index > 0) img.style.display = 'inline-block';
        document.body.appendChild(img);
      }
      img.src = pages[index]; // start loading the data-uri as source
    }
    
    0 讨论(0)
  • 2020-12-29 15:07

    Thank you @user3913960, your concept worked for me. I found some issues in your code which I fixed. Here is the code:

    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");
    
    0 讨论(0)
提交回复
热议问题