Forked from glenhallworthreadify/How to save a webpage as PDF file using Puppeteer.js
Last active
February 13, 2021 22:32
-
-
Save jmpinit/deecdd06b3dde75cfc1c7009fe2508a8 to your computer and use it in GitHub Desktop.
Save a PDF using Puppeteer given a URL. Run with first argument set to the URL to save as PDF.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const path = require('path'); | |
const url = require('url'); | |
const puppeteer = require('puppeteer'); | |
class Webpage { | |
static async generatePDF(url, filename) { | |
const browser = await puppeteer.launch({ headless: true }); | |
const page = await browser.newPage(); | |
await page.goto(url); | |
const pdfConfig = { | |
path: filename, | |
format: 'A4', | |
printBackground: true, | |
// Word's default A4 margins | |
margin: { | |
top: '2.54cm', | |
bottom: '2.54cm', | |
left: '2.54cm', | |
right: '2.54cm' | |
}, | |
}; | |
await page.emulateMedia('screen'); | |
const pdf = await page.pdf(pdfConfig); | |
await browser.close(); | |
return pdf; | |
} | |
} | |
const [, , theURL] = process.argv; | |
function createUniqueFilename(pathname) { | |
const ext = path.extname(pathname); | |
let filename = `${path.basename(pathname, ext)}.pdf`; | |
let i = 1; | |
while (fs.existsSync(filename)) { | |
filename = `${path.basename(pathname, ext)}_${i}.pdf`; | |
i += 1; | |
} | |
return filename; | |
} | |
(async() => { | |
const urlParsed = url.parse(theURL); | |
const filename = createUniqueFilename(urlParsed.pathname); | |
try { | |
console.log(`Downloading ${theURL} as ${filename}`); | |
await Webpage.generatePDF(theURL, filename); | |
} catch (err) { | |
console.error(err.toString()); | |
process.exit(1); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment