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

Published on December 19, 2016

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 !


Click on the button below to choose a PDF file :

Loading document ...
Loading page ...
Download PNG

Codes for the demo are provided towards the end of this tutorial for download.

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.

// Download button (PNG)
$("#download-image").on('click', function() {
	$(this).attr('href', $('#pdf-canvas').get(0).toDataURL());
	// Specfify download option with name
	$(this).attr('download', 'page.png');

// Download button (JPEG with quality 80%)
$("#download-image").on('click', function() {
	$(this).attr('href', $('#pdf-canvas').get(0).toDataURL("image/jpeg", 0.8));
	// Specfify download option with name
	$(this).attr('download', 'page.jpg');

Download Sample Codes


Explanation of the codes can be found in PDF.JS Tutorial 1.

Browser Compatability

The above code will work good in all major browsers, including Edge.

It can also work in IE 10 & 11 but they do not support the HTML download attribute — the base-64 image data is being generated, but it is not downloadable. If you want to make it work for IE 10 & 11, you have to make a little modification to the code where base-64 image data is being saved

$("#download-image").on('click', function() {
	// For IE 10 & 11
	if(typeof window.navigator.msSaveBlob === 'function')
		window.navigator.msSaveBlob(new Blob( [__CANVAS.msToBlob()], {type: 'image/png'} ), 'page.png');
		$(this).attr('href', __CANVAS.toDataURL()).attr('download', 'page.png');

See Saving files locally using Blob and msSaveBlob and msToBlob method for more.

In this Tutorial
    Loading Comments