PDF.js 'Hello, world!' example

by ph822720355

HTML

<script src="//mozilla.github.io/pdf.js/build/pdf.mjs"></script>

<h1>PDF.js 'Hello, world!' example</h1>

<div id="output">

</div>

CSS

* { 
font-family: "Tahoma";
font-size: 25px;
}

JavaScript

// If absolute URL from the remote server is provided, configure the CORS
// header on that server.
var url = '//cdn.mozilla.net/pdfjs/helloworld.pdf';

// Disable workers to avoid yet another cross-origin issue (workers need
// the URL of the script to be loaded, and dynamically loading a cross-origin
// script does not work).
// PDFJS.disableWorker = true;

// The workerSrc property shall be specified.
PDFJS.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';

// Asynchronous download of PDF
var loadingTask = PDFJS.getDocument(url);
loadingTask.promise.then(function(pdf) {
  console.log('PDF loaded');
  
  // Fetch the first page
  var pageNumber = 1;
  pdf.getPage(pageNumber).then(function(page) {
    console.log('Page loaded');
    
    var scale = 1.5;
    var viewport = page.getViewport(scale);

     return page.getOperatorList().then(function (opList) {
              var svgGfx = new PDFJS.SVGGraphics(page.commonObjs, page.objs);
              return svgGfx.getSVG(opList, viewport).then(function (svg) {
                document.getElementById('output').appendChild(svg);
              });
    });
  });
}, function (reason) {
  // PDF loading error
  console.error(reason);
});