Skip to content

Instantly share code, notes, and snippets.

@magician11
Last active July 27, 2022 18:19
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 magician11/6f71e65df9dcf45cc1f8ce2f24216c6d to your computer and use it in GitHub Desktop.
Save magician11/6f71e65df9dcf45cc1f8ce2f24216c6d to your computer and use it in GitHub Desktop.
How to generating a PDF from HTML using JavaScript
const puppeteer = require('puppeteer');
const htmlToPdf = async html => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// https://pptr.dev/#?product=Puppeteer&version=v13.6.0&show=api-pagesetcontenthtml-options
await page.setContent(html);
// https://pptr.dev/#?product=Puppeteer&version=v13.6.0&show=api-pagepdfoptions
const buffer = await page.pdf({
format: 'A4',
printBackground: true,
displayHeaderFooter: true
});
await browser.close();
return buffer;
};
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous"
/>
<title>${name} statement report</title>
<style>
.sunbowl-blue {
color: #87ceeb !important;
}
#scallops {
background-image: url('https://user-images.githubusercontent.com/3735849/164582296-6e19273d-2d1a-4482-a25c-4edc9c6416ec.png');
background-repeat: repeat-x;
height: 11px;
}
@media print {
table {
font-size: 0.85em;
}
p {
line-height: 1
}
small {
font-size: 0.65em;
}
thead {
display: table-row-group;
}
}
</style>
</head>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment