import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { basename, dirname, extname, resolve } from "node:path"; import { spawn, spawnSync } from "node:child_process"; const inputArg = process.argv[2]; if (!inputArg) { console.error("Usage: npm run pdf -- [output.pdf]"); process.exit(1); } const inputPath = resolve(inputArg); const outputPath = resolve(process.argv[3] ?? `dist/${basename(inputPath, extname(inputPath))}.pdf`); const htmlPath = outputPath.replace(/\.pdf$/i, ".html"); const cssPath = resolve(process.env.PDF_CSS ?? "resume.css"); const markdown = readFileSync(inputPath, "utf8"); const css = readFileSync(cssPath, "utf8"); mkdirSync(dirname(outputPath), { recursive: true }); const html = ` ${escapeHtml(basename(inputPath, extname(inputPath)))}
${renderMarkdown(markdown)}
`; async function printPdfWithChrome(sourceHtmlPath, targetPdfPath) { const chrome = findChrome(); const userDataDir = mkdtempSync(resolve(tmpdir(), "resume-chrome-")); const chromeProcess = spawn(chrome, [ "--headless", "--disable-gpu", "--no-sandbox", "--remote-debugging-port=0", `--user-data-dir=${userDataDir}`, "about:blank", ], { stdio: ["ignore", "ignore", "pipe"], }); let stderr = ""; chromeProcess.stderr.on("data", (chunk) => { stderr += chunk.toString(); }); try { const browserWsUrl = await readBrowserWsUrl(userDataDir, chromeProcess); const tab = await createTab(browserWsUrl, `file://${sourceHtmlPath}`); const pdfBase64 = await printTabToPdf(tab.webSocketDebuggerUrl); writeFileSync(targetPdfPath, Buffer.from(pdfBase64, "base64")); } catch (error) { console.error(error.message); if (stderr.trim()) { console.error(stderr.trim()); } process.exitCode = 1; } finally { chromeProcess.kill("SIGTERM"); if (chromeProcess.exitCode === null) { await new Promise((resolveExit) => chromeProcess.once("exit", resolveExit)); } try { rmSync(userDataDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } catch (error) { if (error?.code !== "ENOTEMPTY" && error?.code !== "EBUSY") { throw error; } } } if (process.exitCode) { process.exit(process.exitCode); } } async function readBrowserWsUrl(userDataDir, chromeProcess) { const activePortPath = resolve(userDataDir, "DevToolsActivePort"); for (let attempt = 0; attempt < 100; attempt += 1) { if (chromeProcess.exitCode !== null) { throw new Error(`Chrome exited before DevTools became available. Exit code: ${chromeProcess.exitCode}`); } try { const [port, path] = readFileSync(activePortPath, "utf8").trim().split("\n"); return `ws://127.0.0.1:${port}${path}`; } catch { await delay(50); } } throw new Error("Timed out while waiting for Chrome DevTools."); } async function createTab(browserWsUrl, url) { const browser = new CdpClient(browserWsUrl); await browser.open(); const { targetId } = await browser.send("Target.createTarget", { url }); await browser.close(); const targetsUrl = `http://${new URL(browserWsUrl).host}/json/list`; for (let attempt = 0; attempt < 100; attempt += 1) { const targets = await fetch(targetsUrl).then((response) => response.json()); const tab = targets.find((target) => target.id === targetId); if (tab?.webSocketDebuggerUrl) { return tab; } await delay(50); } throw new Error("Timed out while opening the HTML tab."); } async function printTabToPdf(tabWsUrl) { const tab = new CdpClient(tabWsUrl); await tab.open(); await tab.send("Page.enable"); await delay(300); await tab.send("Page.getLayoutMetrics"); const result = await tab.send("Page.printToPDF", { displayHeaderFooter: false, printBackground: true, preferCSSPageSize: true, }); await tab.close(); return result.data; } class CdpClient { constructor(url) { this.url = url; this.nextId = 1; this.pending = new Map(); } open() { return new Promise((resolveOpen, rejectOpen) => { this.ws = new WebSocket(this.url); this.ws.onopen = () => resolveOpen(); this.ws.onerror = () => rejectOpen(new Error(`Failed to connect to ${this.url}`)); this.ws.onmessage = (event) => { const message = JSON.parse(event.data); const pending = this.pending.get(message.id); if (!pending) { return; } this.pending.delete(message.id); if (message.error) { pending.reject(new Error(message.error.message)); } else { pending.resolve(message.result); } }; }); } send(method, params = {}) { const id = this.nextId; this.nextId += 1; const payload = JSON.stringify({ id, method, params }); return new Promise((resolveSend, rejectSend) => { this.pending.set(id, { resolve: resolveSend, reject: rejectSend }); this.ws.send(payload); }); } close() { this.ws.close(); } } function delay(ms) { return new Promise((resolveDelay) => setTimeout(resolveDelay, ms)); } function findChrome() { const candidates = [ process.env.CHROME_BIN, "google-chrome", "google-chrome-stable", "chromium", "chromium-browser", ].filter(Boolean); for (const candidate of candidates) { const found = spawnSync("which", [candidate], { encoding: "utf8" }); if (found.status === 0) { return found.stdout.trim(); } } console.error("Chrome executable not found. Install Google Chrome or Chromium first."); process.exit(1); } function renderMarkdown(source) { const lines = source.replace(/\r\n/g, "\n").split("\n"); const blocks = []; for (let index = 0; index < lines.length;) { const line = lines[index]; if (!line.trim()) { index += 1; continue; } const heading = /^(#{1,3})\s+(.+)$/.exec(line); if (heading) { const level = heading[1].length; blocks.push(`${inline(heading[2])}`); index += 1; continue; } if (/^---+$/.test(line.trim())) { blocks.push("
"); index += 1; continue; } if (/^\`\`\`/.test(line.trim())) { const fence = line.trim(); const language = fence.slice(3).trim(); const codeLines = []; index += 1; while (index < lines.length && !/^\`\`\`/.test(lines[index].trim())) { codeLines.push(lines[index]); index += 1; } if (index < lines.length) { index += 1; } const languageClass = language ? ` class="language-${escapeHtml(language)}"` : ""; blocks.push(`
${escapeHtml(codeLines.join("\n"))}
`); continue; } const image = /^!\[([^\]]*)\]\(([^)]+)\)$/.exec(line.trim()); if (image) { const alt = image[1]; const caption = alt.replace(/^(FULL|CHART|WIDE|TOPOLOGY|STATE|SMALL)\s*ยท?\s*/, "").trim(); const imagePath = resolve(dirname(inputPath), image[2]); const figcaption = caption ? `
${escapeHtml(caption)}
` : ""; blocks.push(`
${escapeHtml(alt)}${figcaption}
`); index += 1; continue; } if (isTableStart(lines, index)) { const rows = []; rows.push(parseTableRow(lines[index])); index += 2; while (index < lines.length && /^\|.*\|$/.test(lines[index].trim())) { rows.push(parseTableRow(lines[index])); index += 1; } blocks.push(renderTable(rows)); continue; } if (line.startsWith(">")) { const quoteLines = []; while (index < lines.length && lines[index].startsWith(">")) { quoteLines.push(lines[index].replace(/^>\s?/, "")); index += 1; } blocks.push(`
${renderParagraphs(quoteLines)}
`); continue; } if (/^-\s+/.test(line)) { const items = []; while (index < lines.length && /^-\s+/.test(lines[index])) { items.push(lines[index].replace(/^-\s+/, "")); index += 1; } blocks.push(``); continue; } if (/^\d+\.\s+/.test(line)) { const items = []; while (index < lines.length && /^\d+\.\s+/.test(lines[index])) { items.push(lines[index].replace(/^\d+\.\s+/, "")); index += 1; } blocks.push(`
    ${items.map((item) => `
  1. ${inline(item)}
  2. `).join("")}
`); continue; } const paragraph = []; while ( index < lines.length && lines[index].trim() && !/^(#{1,3})\s+/.test(lines[index]) && !/^---+$/.test(lines[index].trim()) && !/^\`\`\`/.test(lines[index].trim()) && !lines[index].startsWith(">") && !/^- /.test(lines[index]) && !/^\d+\.\s+/.test(lines[index]) && !/^!\[[^\]]*\]\([^)]+\)$/.test(lines[index].trim()) && !isTableStart(lines, index) ) { paragraph.push(lines[index].trim()); index += 1; } blocks.push(`

${inline(paragraph.join(" "))}

`); } return groupPages(groupProjectSections(blocks)).map((block) => ` ${block}`).join("\n"); } /** * Wrap every

and the blocks that follow it in a fixed-height page box. * The page box is a flex column, which lets its figure claim whatever vertical * space the text on that page leaves over instead of being capped by a guess. */ function groupPages(blocks) { const pages = []; let current = null; for (const block of blocks) { if (block.startsWith("

")) { if (current) { pages.push(current); } current = [block]; continue; } if (current) { current.push(block); } else { pages.push([block]); } } if (current) { pages.push(current); } return pages.map((page) => `
${page.join("")}
`); } function groupProjectSections(blocks) { const grouped = []; for (let index = 0; index < blocks.length;) { if (!blocks[index].startsWith("

")) { grouped.push(blocks[index]); index += 1; continue; } const section = []; while ( index < blocks.length && !blocks[index].startsWith("

") && !blocks[index].startsWith("

") && (section.length === 0 || !blocks[index].startsWith("

")) ) { section.push(blocks[index]); index += 1; } grouped.push(`
${section.join("")}
`); } return grouped; } function renderParagraphs(lines) { return lines .join("\n") .split(/\n\s*\n/) .map((paragraph) => `

${inline(paragraph.replace(/\n/g, " ").trim())}

`) .join(""); } function isTableStart(lines, index) { return ( index + 1 < lines.length && /^\|.*\|$/.test(lines[index].trim()) && /^\|\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?$/.test(lines[index + 1].trim()) ); } function parseTableRow(line) { return line .trim() .replace(/^\|/, "") .replace(/\|$/, "") .split("|") .map((cell) => cell.trim()); } function renderTable(rows) { const columns = rows[0]?.length ?? 0; const className = columns === 3 ? "metric-table" : columns === 2 ? "two-col-table" : "data-table"; return `${rows .map((row) => `${row.map((cell) => ``).join("")}`) .join("")}
${inline(cell)}
`; } function inline(value) { return escapeHtml(value) .replace(/`([^`]+)`/g, "$1") .replace(/\*\*([^*]+)\*\*/g, "$1") .replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g, '$1'); } function escapeHtml(value) { return value .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """); } writeFileSync(htmlPath, html); await printPdfWithChrome(htmlPath, outputPath); console.log(`HTML: ${htmlPath}`); console.log(`PDF: ${outputPath}`);