generated from revanth0212/api-mesh-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconvertHTMLToPDF.js
More file actions
52 lines (40 loc) · 1.31 KB
/
convertHTMLToPDF.js
File metadata and controls
52 lines (40 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const puppeteer = require('puppeteer');
const fs = require('fs');
const htmlFileName = process.argv[2];
if (!htmlFileName) {
console.error('Please provide the HTML file name to convert to PDF');
process.exit(1);
}
const pdfFileName = htmlFileName.replace('.html', '.pdf');
console.log(`Converting ${htmlFileName} to ${pdfFileName}`);
async function convertHTMLReportToPDF() {
// Create a browser instance
const browser = await puppeteer.launch();
// Create a new page
const page = await browser.newPage();
//Get HTML content from HTML file
const html = fs.readFileSync(htmlFileName, 'utf-8');
await page.setContent(html, { waitUntil: 'domcontentloaded' });
// To reflect CSS used for screens instead of print
await page.emulateMediaType('screen');
// Downlaod the PDF
await page.pdf({
path: pdfFileName,
margin: { top: '100px', right: '50px', bottom: '100px', left: '50px' },
printBackground: true,
format: 'A4',
});
// Close the browser instance
await browser.close();
}
convertHTMLReportToPDF()
.then(() => {
console.log(`PDF generated at ${pdfFileName}`);
// read the PDF file size
const stats = fs.statSync(pdfFileName);
const fileSizeInBytes = stats.size;
console.log(`PDF file size: ${fileSizeInBytes} bytes`);
})
.catch(error => {
console.error(`Error occurred: ${error}`);
});