Skip to content

Instantly share code, notes, and snippets.

@romaricpascal
Created June 14, 2022 18:02
Show Gist options
  • Save romaricpascal/311bc6519a6f1ff96287592f6a41f49e to your computer and use it in GitHub Desktop.
Save romaricpascal/311bc6519a6f1ff96287592f6a41f49e to your computer and use it in GitHub Desktop.
Puppeprint
import express from 'express';
import puppeteer from "puppeteer";
const app = express();
const port = process.env.PORT || 8080;
async function makePDF(url) {
console.log('Creating PDF', url);
const browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"],
});
const page = await browser.newPage();
await page.goto(url, {
waitUntil: "networkidle2",
});
const buffer = await page.pdf({ format: "a4" });
await browser.close();
return buffer;
}
app.get("/", async (req, res) => {
if (req.query.url) {
const pdf = await makePDF(req.query.url);
console.log('Generated pdf', pdf);
res.setHeader('Content-Type', 'application/pdf');
res.send(pdf);
} else {
res.send('Please provide a URL parameter');
}
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
{
"name": "puppeprint",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"type": "module",
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.1",
"puppeteer": "^14.4.0"
},
"devDependencies": {
"nodemon": "^2.0.16"
}
}
@romaricpascal
Copy link
Author

romaricpascal commented Jun 14, 2022

Quick use of Express + Puppeteer to get a printing as a service prototype. Improvements include:

Requires jontewks/puppeteer-heroku-buildpack to run on Heroku

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