Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jmpinit/deecdd06b3dde75cfc1c7009fe2508a8 to your computer and use it in GitHub Desktop.
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.
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