JSFiddle - React, Tailwind, and code Playground

PDF.js Demo with Web Workers and Image Scaling

by skibulk

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.474/pdf.js"></script>
<input id="browse" type="file">

CSS

canvas {
  display: block;
}

html:hover {
  background: gray;
}

JavaScript

/* To-Do:
Use Queue
Toggle bleed area
https://stackoverflow.com/q/28855900/6465140
*/

// Create shortcut to PDF.js exports
var pdfjsLib = window['pdfjs-dist/build/pdf'];

// The PDF.js web worker url
// Will be used to load and parse PDF files
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.474/pdf.worker.js';

// Convert a class or function into a web worker
function toWorker(fn) {

  // Web Workers require a file URL to instantiate
  // Create a blob file / url to satisfy the web worker
  var url = URL.createObjectURL(
    new Blob([
      '(' + fn.toString() + ')();'
    ], {
      type: 'application/javascript'
    })
  );

  // Initialize the web worker and release the blob file / url from memory
  var w = new Worker(url);
  URL.revokeObjectURL(url);
  url = null;
  return w;
}

// Read and Convert a file into a binary array
function fileConverter() {

  // Receive the file
  onmessage = function(event) {

    //console.log("fileConverter Received a File", event);
    // Read the file
    var fileReader = new FileReader();
    fileReader.onload = function(event) {

      // convert a file into something that pdf.js can use
      var typedarray = new Uint8Array(this.result);
      //console.log("File conversion successful", event);
      postMessage(typedarray, [typedarray.buffer]);
    };

    fileReader.readAsArrayBuffer(event.data);
  };
}

// Instantiate fileConverter as a web worker
var myWorker = toWorker(fileConverter);

// Receive a binary file array from fileConverter and pass to pdf.js
myWorker.onmessage = function() {

  //console.log("Byte Array Received", event);

  // Using DocumentInitParameters object to load binary data.
  var loadingTask = pdfjsLib.getDocument(event.data);
  loadingTask.promise.then(function(pdf) {
    console.log('PDF loaded');

    for (var i = 1; i <= pdf.numPages; i++) {
      // Fetch the first page
      pdf.getPage(i).then(function(page) {
        console.log('Page...