Skip to content

Instantly share code, notes, and snippets.

@grantmichaels
Created May 13, 2012 19:03
Show Gist options
  • Save grantmichaels/2689773 to your computer and use it in GitHub Desktop.
Save grantmichaels/2689773 to your computer and use it in GitHub Desktop.
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.');
@malipetek
Copy link

How about converting an existing pdf to png?

@rolfen
Copy link

rolfen commented May 31, 2018

malipetek just go to line 42 and replace ./output/"+filename+".pdf" with the path to your pdf file, and comment out the pdf creation code that precedes.

@arthabus
Copy link

arthabus commented Mar 8, 2020

is there a way to write the resulting png directly to a variable without the output file?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment