Skip to content

Instantly share code, notes, and snippets.

@NicolasZanotti
Created January 10, 2012 16:41
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save NicolasZanotti/1589937 to your computer and use it in GitHub Desktop.
Save NicolasZanotti/1589937 to your computer and use it in GitHub Desktop.
Render HTML content to a PDF file with wkhtmltopdf and Node.js
var http = require('http');
var sys = require('sys');
var exec = require('child_process').exec;
var util = require('util');
var fs = require('fs');
http.createServer(function(request, response) {
var dummyContent = '<!doctype html><html><head><title>Test</title><meta charset="utf-8"></head><body><p>Hello world!</p></body></html>';
var htmlFileName = "page.html", pdfFileName = "page.pdf";
// Save to HTML file
fs.writeFile(htmlFileName, dummyContent, function(err) {
if(err) { throw err; }
util.log("file saved to site.html");
});
// Convert HTML to PDF with wkhtmltopdf (http://code.google.com/p/wkhtmltopdf/)
var child = exec("wkhtmltopdf " + htmlFileName + " " + pdfFileName, function(err, stdout, stderr) {
if(err) { throw err; }
util.log(stderr);
});
response.writeHead(200, {'Content-Type' : 'text/plain'});
response.end('Rendered to ' + htmlFileName + ' and ' + pdfFileName + '\n');
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
@NicolasZanotti
Copy link
Author

Should also work with wkpdf from http://plessl.github.com/wkpdf/

Copy link

ghost commented Jun 4, 2013

Hello, I am brand new to node.js and all its environment, so do we need to install wkhtmltopdf using a "npm install" and then run your gist and everything will be fine ?
Thanks in advance

@merunga
Copy link

merunga commented Jul 11, 2013

wkhtmltopdf is an stand alone command line tool, you should download it from here https://code.google.com/p/wkhtmltopdf/

@pitambar
Copy link

i am using ubantu,
how to save pdf in a folder,in a sever as well as on client side,
here the log output
Server running at http://127.0.0.1:8124/
err Error: Command failed: /bin/sh -c wkhtmltopdf page.html page.pdf
/bin/sh: wkhtmltopdf: not found

28 Apr 20:01:40 - /bin/sh: wkhtmltopdf: not found

28 Apr 20:01:40 - file saved to site.html
err Error: Command failed: /bin/sh -c wkhtmltopdf page.html page.pdf
/bin/sh: wkhtmltopdf: not found

28 Apr 20:01:40 - /bin/sh: wkhtmltopdf: not found

28 Apr 20:01:40 - file saved to site.html

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