Skip to content

Instantly share code, notes, and snippets.

@adamtaylor13
Created March 18, 2023 05:50
Show Gist options
  • Save adamtaylor13/abd608ee9fa903bb5c674004a2fbea04 to your computer and use it in GitHub Desktop.
Save adamtaylor13/abd608ee9fa903bb5c674004a2fbea04 to your computer and use it in GitHub Desktop.
Generate resume PDF from an HTML web page
const puppeteer = require('puppeteer');
const path = require("path");
const absolutePath = path.resolve(__filename);
const assetDirectory = path.join(absolutePath, "../public/assets/");
const http = require('http');
const options = {
host: 'localhost',
port: 3000,
timeout: 1000,
};
const httpFailure = () => {
console.error("❌ Error connecting to localhost. Is the local dev server running? Hint: Start the local server with `yarn dev`");
process.exit(1);
}
// Make sure localhost is up before trying to run
const req = http.request(options);
req.on('error', httpFailure);
req.end();
/**
* This function utilizes puppeteer to generate a PDF of the resume page.
* This allows us to distrubute a PDF version of the resume that is always
* up-to-date with the latest changes on the website.
*
* This script requires that the local localhost is running.
* Hint: Use `yarn dev` to start the local server.
*/
(async () => {
console.log("⏱ Starting up Puppeteer browser");
const width = 1920;
const height = 3000;
const browser = await puppeteer.launch({
headless: true,
args: [
`--window-size=${width},${height}`,
"--remote-debugging-port=9229",
],
defaultViewport: {
width,
height,
hasTouch: false,
isLandscape: false,
isMobile: false,
},
// This prevents the popup asking if we want to allow connections
executablePath:
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
});
const page = await browser.newPage();
const website_url = 'http://localhost:3000/resume';
await page.goto(website_url, { waitUntil: 'networkidle0' });
console.log("🔧 Applying pdf-render adjustments");
// To reflect CSS used for screens instead of print
await page.emulateMediaType('screen');
await page.evaluate(() => {
const htmlElement = document.querySelector("html");
// This class prevents us from rendering elements with ".no-pdf-render"
// and consequently WILL render elements with ".render-pdf"
htmlElement.classList.add("pdf-render");
htmlElement.setAttribute("data-theme", "dark");
});
// This actually downloads the PDF to the specified path
await page.pdf({
path: assetDirectory + `my_resume_latest.pdf`,
printBackground: true,
scale: 0.8,
});
console.log("✅ PDF Generated");
await browser.close();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment