Skip to content

Instantly share code, notes, and snippets.

@krnlde
Last active August 29, 2015 14:23
Show Gist options
  • Save krnlde/ba4020aa309f06f68ecd to your computer and use it in GitHub Desktop.
Save krnlde/ba4020aa309f06f68ecd to your computer and use it in GitHub Desktop.
This script handles HTTP POST requests and returns a generated, streamed PDF filled with the contents of the POST. You need to install wkhtmltopdf globally on your system first. You can either provide form data key value pairs or JSON data. It'll both be parsed to JSON and put into handlebars. Install all the imports via npm.
"use strict";
import fs from 'fs';
import express from 'express';
import bodyParser from 'body-parser';
import Handlebars from 'handlebars';
import wkhtmltopdf from 'wkhtmltopdf';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.post('/makepdf', (req, res) => {
fs.readFile('pdf-template.html', (err, contentBuffer) => {
if (err) {
console.error(err);
return res.end('failed');
}
const template = Handlebars.compile(contentBuffer.toString('utf8'));
wkhtmltopdf(template(req.body)).pipe(res);
});
});
app.listen(3000, () => {
console.log('Listening on 3000');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment