Jørgen Rasmussen
Jørgen Rasmussen

Reputation: 1353

Convert a PDF to thumbnail using PDF.JS

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.

I have a HTML file that looks like this

<!DOCTYPE html>
<html>

<head>
    <title>JR PDF test</title>
</head>

<body>
    <script type="text/javascript" src="/build/pdf.js"></script>
    <script type="text/javascript" src="jr-pdf.js"></script>
    <script type="text/javascript" src="canvas2image.js"></script>
</body>

<div id="pdf-main-container">
    <a id="download-image" href="#">Download PNG</a>
</div>
</div>

</html>

<canvas id="the-canvas"></canvas>

and a the jr-pdf.js looks like this

// 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);
  });

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).

So I guess these lines are wrong:

url = canvas.toDataURL();

downloadButton = document.getElementById('download-image');
downloadButton.setAttribute('download', 'jr.png');
downloadButton.setAttribute('href', url); 

Any suggestions on how to make a correct PNG file?

Upvotes: 3

Views: 5412

Answers (1)

async5
async5

Reputation: 2691

page.render is asynchronous function -- you need to wait until it finishes painting

var renderTask = page.render(renderContext);
renderTask.promise.then(function () {
    // use canvas now
    var url = canvas.toDataURL();

    var downloadButton = document.getElementById('download-image');
    downloadButton.setAttribute('download', 'jr.png');
    downloadButton.setAttribute('href', url);      
});

Upvotes: 4

Related Questions