Menu

1 / 2

HTML to PDF with headless Chrome in Node.js, without Puppeteer

DEV Community: javascript·Rushi Patel·5 days ago
#GmpgyYrm
#devtojavascript#devto#dev#it#chrome
Reading 0:00
15s threshold

You can turn any HTML into a print-ready PDF with headless Chrome and about 60 lines of Node.js , no Puppeteer and no npm packages: start Chrome with a debugging port, open its WebSocket, and send two DevTools Protocol commands, Page.navigate and Page.printToPDF . Here is the whole script, the CSS that makes the page size right, and four things that go wrong.

We use exactly this on Triplli , our sister product for travel agencies, to make its free downloads: a blank and a filled itinerary format and a payment receipt format , each printed from the same HTML that the guide page shows. The document is drawn once, in HTML, and the PDF, the picture and the page can never disagree.

Why not Puppeteer

Puppeteer is fine, and it downloads its own copy of Chrome on install. For a build script that prints a handful of documents from a Chrome already on the machine, the Chrome DevTools Protocol (CDP) directly is smaller and has nothing to keep up to date.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.