Create thumbnails of PDF’s with Node JS and GraphicsMagick

1. Install GraphicsMagick

On Ubuntu (14.04):

sudo apt-get install graphicsmagick


2. Install the Node library in your project

npm install gm


3. Write  a script

Below I show two ways of creating a thumbnail. The first way creates a JPG using various GraphicsMagick functions, I prefer this way because it gives me fine grained control over the thumbnail. The second uses a built in function for thumbnails, which is easy to use but isn’t as flexible.

var gm = require('gm');
// Create JPG from page 0 of the PDF
gm("file.pdf[0]") // The name of your pdf
.resize(200) // Resize to fixed 200px width, maintaining aspect ratio
.quality(75) // Quality from 0 to 100
.write("/tmp/cover.jpg", function(error){
// Callback function executed when finished
if (!error) {
console.log("Finished saving JPG");
} else {
console.log("There was an error!", error);
// Create a PNG using thumbnail function
200, // Width
200, // Height
'/tmp/thumbnail.png', // Output file name
80, // Quality from 0 to 100
function (error, stdout, stderr, command) {
if (!error) {
} else {

view raw


hosted with ❤ by GitHub

The main problem with the second method is that there is no automatic way of maintaining the aspect ratio. You’d have to do some math on your own first.

If you have any suggestions for improving the code or have any issues/errors running it, please leave a comment below.


2 thoughts on “Create thumbnails of PDF’s with Node JS and GraphicsMagick

  1. Hi! This and other similar versions I find elsewhere doesn’t work for me. When I look up supported formats in GraphicsMagick it does show that PDFs are supported but that they require ghostscript, yet your instructions doesn’t mention it so I wonder if you had to do it too, or if you’re aware of any other reason why it might not work.

    I basically get a “unable to open” error message, or when I try to call on toBuffer() it says “steam yields empty buffer” and I’ve tried numerous ways of saving the pdf and loading it into gm with similar results, which makes me believe that the culprit is ghostscript

    • Yes, ghostscript is required and in most cases is automatically installed with GraphicsMagick. If not, you’ll have to install it as well on your system. Many of the GM functions depend on GS to work. PDF rendering definitely needs GS to work properly.

What are your thoughts?

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s