Skip to content

Instantly share code, notes, and snippets.

@amenophis
Last active October 26, 2022 08:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amenophis/1ef3886620c9cb698cc49c987e008ee5 to your computer and use it in GitHub Desktop.
Save amenophis/1ef3886620c9cb698cc49c987e008ee5 to your computer and use it in GitHub Desktop.
htmltopdf with pupeteer and chrome

htmltopdf with pupeteer and chrome

Install

Install project dependencies:

yarn

Start

yarn start

Usage

Do an http call on http://localhost:8080/convert with the following payload:

{
    "content": "<div><h1>Content</h1></div>"
}

The service will respond with a 200 OK response, and the payload will be the PDF binary

require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const puppeteer = require('puppeteer-core');
const server = async function() {
const app = express();
const port = process.env.PORT || 8080;
app.use(bodyParser.json({
type: 'application/json',
limit: '5mb'
}));
app.post('/convert', async function(req, res) {
const browser = await puppeteer.launch({
executablePath: process.env.CHROME_EXEC || 'google-chrome',
headless: true,
args: [
'--no-sandbox',
'--disable-gpu'
]
});
const page = await browser.newPage();
const { content } = req.body;
await page.setContent(content);
let options = {
format: "A4",
};
const pdfContentBuffer = await page.pdf(options);
res.append('Content-Type', 'application/pdf');
res.append('Content-Length', pdfContentBuffer.length);
await browser.close();
res.send(pdfContentBuffer);
});
app.listen(port, function() {
console.log('listening on port ' + port)
})
};
server();
{
"name": "htmltopdf",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"puppeteer-core": "1.20.0"
},
"devDependencies": {},
"engines": {
"node": ">=14.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment