Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PDF to PNG with Node.js and GhostScript
var exec = require('child_process').exec;
var fs = require('fs');
var util = require('util');
var http = require('http');
var url = require('url');
var PDFDocument = require('pdfkit'); // http://pdfkit.org/
http.createServer(function (req, res) {
// Parse URL to get a filename
var urlObj = url.parse(req.url, true);
var filename = urlObj.query["filename"];
// Create a PDF with PDFKit
var doc = new PDFDocument({
size: 'A4',
layout: 'portrait'
});
doc.fontSize(22);
doc.text('Your file: '+filename+'.pdf', 20, 20);
doc.fontSize(16);
doc.text('Was created successfully if you see this.', 20, 30);
doc.save();
doc.moveTo(100, 150);
doc.lineTo(100, 250);
doc.lineTo(200, 250);
doc.fill("#FF3300");
doc.restore();
doc.write("./output/"+filename+".pdf");
// Render PNG with GhostScript
exec("/usr/bin/gs -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT -sDEVICE=png16m -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r72 -dFirstPage=1 -dLastPage=1 -sOutputFile=./output/"+filename+".png ./output/"+filename+".pdf", function (error, stdout, stderr) {
if ( error !== null ) {
console.log(error);
}
else {
var img = fs.readFileSync('./output/'+filename+'.png');
res.writeHead(200, {'Content-Type': 'image/png' });
res.end(img, 'binary');
console.log('Created PNG: '+filename+'.png');
}
});
}).listen(3000);
console.log('Server running.');
@bparvizi

This comment has been minimized.

Copy link

bparvizi commented Mar 19, 2014

Fantastic, thanks for this!

@lekhnath

This comment has been minimized.

Copy link

lekhnath commented Jan 23, 2015

WOW. But, write method has been deprecated in newer (v0.7.0) version of pdfkit. Here is an update (https://gist.github.com/lekhnath/2f4d696548bdb71195d4).

@NickNaso

This comment has been minimized.

Copy link

NickNaso commented Mar 2, 2017

When you call Ghostscript consider to use Ghostscript4JS it's a module that binds the Ghostscript C command API to bring its power to the Node.JS world.
https://www.npmjs.com/package/ghostscript4js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.