Occasionally, our clients need to be able to generate a PDF of a webpage so that their visitors can have a “hard” copy of a page – this is useful for contracts, receipts and the like. We scratched around for off-the-shelf solutions for a while, but most things were one or more of:
- Paid (or added a watermark)
- Didn’t compose a PDF directly from HTML + CSS, i.e. read directly from a URL
After some digging, we came across Fraser Xu’s excellent electron-pdf. electron-pdf is a CLI tool written in NodeJS that spins up a headless instance of Electron (Chromium, in effect) and generates a PDF from the actual rendered contents of a page. It works really well, but with one shortcoming for our purposes: it’s a simple command line tool, and we needed something available on the web to serve up the completed PDF.
With a simple Express server wrapped around the electron-pdf CLI, we’ve created express-electron-pdf – a simple Node server for creating PDFs through a simple GET request.
To start the server, simply:
docker run -d -e "PORT=8080" -e "TOKEN=yoursecrettoken" --name=express-electron-pdf -p 8080:8080 properdesign/express-electron-pdf
Then, to get a PDF (assuming that you’re running on localhost), simply hit https://properdesign.co.uk:8080/?token=yoursecrettoken&url=http://yoursite.com in your browser.
The project still needs plenty of work (particularly in error-handling and the like), but we hope this is the start of something useful.