logo
post image

How to Convert PDF to Image (JPEG / PNG) with Javascript using PDF.JS

In PDF.JS Tutorial 1 we discussed how PDF.JS can be used to show a preview of the PDF. The application can navigate pages of the PDF using PDF.JS APIs.

In Tutorial 2 we discussed how PDF.JS, being a complete PDF viewer, can be also open a password protected PDF.

In Tutorial 3 we discussed about the loading callback, which can be used in showing a progress bar when PDF is being loaded. This can be really helpful in cases where PDF is quite big in size.

In this tutorial we will discuss how we can use PDF.JS to implement the popular feature of PDF to image (JPEG / PNG) conversion. With PDF.JS you don't need a sever side solution to convert PDF to image !

PDF to Image

Once you have rendered the PDF in your appliaction using PDF.JS, converting a PDF page to an image is nothing special. PDF.JS uses a <canvas> element to render a PDF (although it can also be set to use an SVG). You can easily convert the underlying canvas to an image using canvas.toDataURL method.

// PNG
document.querySelector('#pdf-canvas').toDataURL()

// JPEG with quality 80%
document.querySelector('#pdf-canvas').toDataURL("image/jpeg", 0.8)