title: Convert a PDF to thumbnail using PDF.JS
body: <p>I am trying to write some code that converts the first page of a PDF to a PNG thumbnail. I have found several examples here on stackoverflow and other place on the web and it seems like a simple thing to do, but I cannot make it work.</p>
  
  <p>I have a HTML file that looks like this</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  
  &lt;head&gt;
      &lt;title&gt;JR PDF test&lt;/title&gt;
  &lt;/head&gt;
  
  &lt;body&gt;
      &lt;script type="text/javascript" src="/build/pdf.js"&gt;&lt;/script&gt;
      &lt;script type="text/javascript" src="jr-pdf.js"&gt;&lt;/script&gt;
      &lt;script type="text/javascript" src="canvas2image.js"&gt;&lt;/script&gt;
  &lt;/body&gt;
  
  &lt;div id="pdf-main-container"&gt;
      &lt;a id="download-image" href="#"&gt;Download PNG&lt;/a&gt;
  &lt;/div&gt;
  &lt;/div&gt;
  
  &lt;/html&gt;
  
  &lt;canvas id="the-canvas"&gt;&lt;/canvas&gt;
  </code></pre>
  
  <p>and a the jr-pdf.js looks like this</p>
  
  <pre><code>// URL of PDF document
  var url = "REGLEMENT_FOR_RALLY_2012.pdf";
  
  // Asynchronous download PDF
  PDFJS.getDocument(url)
    .then(function(pdf) {
      return pdf.getPage(1);
    })
    .then(function(page) {
      // Set scale (zoom) level
      var scale = 1.5;
  
      // Get viewport (dimensions)
      var viewport = page.getViewport(scale);
  
      // Get canvas#the-canvas
      var canvas = document.getElementById('the-canvas');
  
      // Fetch canvas' 2d context
      var context = canvas.getContext('2d');
  
      // Set dimensions to Canvas
      canvas.height = viewport.height;
      canvas.width = viewport.width;
  
      // Prepare object needed by render method
      var renderContext = {
        canvasContext: context,
        viewport: viewport
      };
  
      // Render PDF page
      page.render(renderContext);
  
      // JR experiments
      console.log('hej');
  
      url = canvas.toDataURL();
  
      downloadButton = document.getElementById('download-image');
      downloadButton.setAttribute('download', 'jr.png');
      downloadButton.setAttribute('href', url);
    });
  </code></pre>
  
  <p>The first page of the PDF file is rendered correctly to the screen and a jr.png file is generated. When I look at the PNG file the header seems right, but when I try to view the file with an image viewer it is empty (actually it is shown as transparent).</p>
  
  <p>So I guess these lines are wrong:</p>
  
  <pre><code>url = canvas.toDataURL();
  
  downloadButton = document.getElementById('download-image');
  downloadButton.setAttribute('download', 'jr.png');
  downloadButton.setAttribute('href', url); 
  </code></pre>
  
  <p>Any suggestions on how to make a correct PNG file?</p>