|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +/** |
| 4 | + * Generate PDFs from /print/ pages using Puppeteer. |
| 5 | + * |
| 6 | + * Usage: |
| 7 | + * - node scripts/generate-pdfs.mjs <slug> # single article |
| 8 | + * - node scripts/generate-pdfs.mjs # all deep dive articles |
| 9 | + * |
| 10 | + * Requires a running server (dev or preview) at localhost:4321. |
| 11 | + * Set PDF_SERVER_URL to override the server base URL. |
| 12 | + */ |
| 13 | + |
| 14 | +import { existsSync, mkdirSync, readFileSync, readdirSync } from 'node:fs' |
| 15 | +import { join, resolve } from 'node:path' |
| 16 | +import puppeteer from 'puppeteer' |
| 17 | + |
| 18 | +// --- Configuration --- |
| 19 | + |
| 20 | +const SERVER_BASE = process.env.PDF_SERVER_URL ?? 'http://localhost:4321' |
| 21 | +const OUTPUT_DIR = resolve('public/downloads/pdfs') |
| 22 | +const ARTICLES_DIR = resolve('src/content/articles') |
| 23 | +const CONTACT_JSON = resolve('src/content/contact.json') |
| 24 | +const slugFilter = process.argv[2] ?? null |
| 25 | + |
| 26 | +// PDF page: US Letter (8.5 × 11 in) |
| 27 | +const MARGIN = { top: '2cm', right: '2cm', bottom: '2.5cm', left: '2cm' } |
| 28 | + |
| 29 | +// Content area in pixels at 96 DPI (for approximate ToC page-number calculation) |
| 30 | +const CM_PER_IN = 2.54 |
| 31 | +const PAGE_HEIGHT_IN = 11 |
| 32 | +const MARGIN_TOP_IN = 2 / CM_PER_IN |
| 33 | +const MARGIN_BOTTOM_IN = 2.5 / CM_PER_IN |
| 34 | +const MARGIN_SIDE_IN = 2 / CM_PER_IN |
| 35 | +const CONTENT_HEIGHT_PX = (PAGE_HEIGHT_IN - MARGIN_TOP_IN - MARGIN_BOTTOM_IN) * 96 |
| 36 | +const CONTENT_WIDTH_PX = (8.5 - 2 * MARGIN_SIDE_IN) * 96 |
| 37 | + |
| 38 | +// --- Templates --- |
| 39 | + |
| 40 | +const contact = JSON.parse(readFileSync(CONTACT_JSON, 'utf-8')).company |
| 41 | + |
| 42 | +const esc = (s) => |
| 43 | + s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"') |
| 44 | + |
| 45 | +const buildHeaderTemplate = (title) => |
| 46 | + `<div style="font-size:9pt; font-family:Arial,Helvetica,sans-serif; width:100%; display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid #ccc; padding-bottom:4px;"> |
| 47 | + <span style="font-weight:bold;">${esc(contact.name)}</span> |
| 48 | + <span style="color:#555; max-width:60%; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; text-align:right;">${esc(title)}</span> |
| 49 | + </div>` |
| 50 | + |
| 51 | +const footerTemplate = |
| 52 | + `<div style="font-size:8pt; font-family:Arial,Helvetica,sans-serif; width:100%; border-top:1px solid #ccc; padding-top:4px;"> |
| 53 | + <div style="display:flex; justify-content:space-between; margin-bottom:4px;"> |
| 54 | + <span>${esc(contact.address)}, ${esc(contact.city)}, ${esc(contact.state)} ${esc(contact.index)}</span> |
| 55 | + <span>${esc(contact.email)}</span> |
| 56 | + </div> |
| 57 | + <div style="text-align:center; color:#555;"> |
| 58 | + Page <span class="pageNumber"></span> of <span class="totalPages"></span> |
| 59 | + </div> |
| 60 | + </div>` |
| 61 | + |
| 62 | +// --- Slug collection --- |
| 63 | + |
| 64 | +const collectAllSlugs = () => { |
| 65 | + if (!existsSync(ARTICLES_DIR)) return [] |
| 66 | + return readdirSync(ARTICLES_DIR, { withFileTypes: true }) |
| 67 | + .filter(e => e.isDirectory() && existsSync(join(ARTICLES_DIR, e.name, 'pdf.mdx'))) |
| 68 | + .map(e => e.name) |
| 69 | + .sort() |
| 70 | +} |
| 71 | + |
| 72 | +// --- Server check --- |
| 73 | + |
| 74 | +const checkServer = async () => { |
| 75 | + try { |
| 76 | + await fetch(SERVER_BASE, { signal: AbortSignal.timeout(5000) }) |
| 77 | + return true |
| 78 | + } catch { |
| 79 | + return false |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +// --- PDF generation --- |
| 84 | + |
| 85 | +const generatePdf = async (browser, slug) => { |
| 86 | + const inputUrl = `${SERVER_BASE}/print/${slug}` |
| 87 | + const outputPdf = join(OUTPUT_DIR, `${slug}.pdf`) |
| 88 | + |
| 89 | + console.log(` ${slug}`) |
| 90 | + console.log(` input: ${inputUrl}`) |
| 91 | + console.log(` output: ${outputPdf}`) |
| 92 | + |
| 93 | + const page = await browser.newPage() |
| 94 | + |
| 95 | + try { |
| 96 | + // Viewport matches PDF content area for more accurate measurement |
| 97 | + await page.setViewport({ |
| 98 | + width: Math.round(CONTENT_WIDTH_PX), |
| 99 | + height: Math.round(CONTENT_HEIGHT_PX), |
| 100 | + }) |
| 101 | + |
| 102 | + await page.goto(inputUrl, { waitUntil: 'networkidle0', timeout: 60_000 }) |
| 103 | + await page.emulateMediaType('print') |
| 104 | + |
| 105 | + // Wait for all images to finish loading |
| 106 | + await page.evaluate(() => |
| 107 | + Promise.all( |
| 108 | + Array.from(document.images) |
| 109 | + .filter(img => !img.complete) |
| 110 | + .map(img => new Promise(r => { img.onload = r; img.onerror = r })) |
| 111 | + ) |
| 112 | + ) |
| 113 | + |
| 114 | + const title = await page.evaluate(() => document.title) |
| 115 | + |
| 116 | + // Inject approximate page numbers into the ToC |
| 117 | + await page.evaluate((contentH) => { |
| 118 | + const toc = document.querySelector('.print-toc') |
| 119 | + const article = document.querySelector('.print-article') |
| 120 | + if (!toc || !article) return |
| 121 | + |
| 122 | + // Cover always occupies 1 page (break-after: page) |
| 123 | + const coverPages = 1 |
| 124 | + const tocPages = Math.max(1, Math.ceil(toc.getBoundingClientRect().height / contentH)) |
| 125 | + const pagesBeforeArticle = coverPages + tocPages |
| 126 | + |
| 127 | + const articleTop = article.getBoundingClientRect().top |
| 128 | + const pageMap = new Map() |
| 129 | + |
| 130 | + for (const h of article.querySelectorAll('h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]')) { |
| 131 | + const offset = h.getBoundingClientRect().top - articleTop |
| 132 | + pageMap.set(h.id, pagesBeforeArticle + Math.floor(Math.max(0, offset) / contentH) + 1) |
| 133 | + } |
| 134 | + |
| 135 | + for (const span of document.querySelectorAll('.print-toc__page')) { |
| 136 | + const href = span.closest('a')?.getAttribute('href')?.replace('#', '') |
| 137 | + if (href && pageMap.has(href)) { |
| 138 | + span.textContent = String(pageMap.get(href)) |
| 139 | + } |
| 140 | + } |
| 141 | + }, CONTENT_HEIGHT_PX) |
| 142 | + |
| 143 | + // Generate PDF |
| 144 | + await page.pdf({ |
| 145 | + path: outputPdf, |
| 146 | + format: 'Letter', |
| 147 | + margin: MARGIN, |
| 148 | + displayHeaderFooter: true, |
| 149 | + headerTemplate: buildHeaderTemplate(title), |
| 150 | + footerTemplate, |
| 151 | + printBackground: true, |
| 152 | + preferCSSPageSize: false, |
| 153 | + tagged: true, |
| 154 | + outline: true, |
| 155 | + }) |
| 156 | + |
| 157 | + console.log(' ✓ done\n') |
| 158 | + return true |
| 159 | + } catch (error) { |
| 160 | + console.error(` ✗ FAILED: ${error.message ?? error}\n`) |
| 161 | + return false |
| 162 | + } finally { |
| 163 | + await page.close() |
| 164 | + } |
| 165 | +} |
| 166 | + |
| 167 | +// --- Main --- |
| 168 | + |
| 169 | +mkdirSync(OUTPUT_DIR, { recursive: true }) |
| 170 | + |
| 171 | +if (!(await checkServer())) { |
| 172 | + console.error(`ERROR: No server running at ${SERVER_BASE}`) |
| 173 | + console.error('Start the dev server (npm run dev) or preview server (npm run preview) first.') |
| 174 | + process.exit(1) |
| 175 | +} |
| 176 | + |
| 177 | +if (slugFilter) { |
| 178 | + const pdfMdx = join(ARTICLES_DIR, slugFilter, 'pdf.mdx') |
| 179 | + if (!existsSync(pdfMdx)) { |
| 180 | + console.error(`ERROR: No pdf.mdx found for "${slugFilter}"`) |
| 181 | + console.error(`Expected: ${pdfMdx}`) |
| 182 | + process.exit(1) |
| 183 | + } |
| 184 | +} |
| 185 | + |
| 186 | +const slugs = slugFilter ? [slugFilter] : collectAllSlugs() |
| 187 | + |
| 188 | +if (slugs.length === 0) { |
| 189 | + console.error('ERROR: No deep dive articles with pdf.mdx found.') |
| 190 | + process.exit(1) |
| 191 | +} |
| 192 | + |
| 193 | +console.log(`Generating ${slugs.length} PDF(s) from ${SERVER_BASE}...\n`) |
| 194 | + |
| 195 | +const browser = await puppeteer.launch({ |
| 196 | + headless: true, |
| 197 | + args: ['--no-sandbox', '--disable-setuid-sandbox'], |
| 198 | +}) |
| 199 | + |
| 200 | +let succeeded = 0 |
| 201 | +let failed = 0 |
| 202 | + |
| 203 | +try { |
| 204 | + for (const slug of slugs) { |
| 205 | + const ok = await generatePdf(browser, slug) |
| 206 | + if (ok) succeeded++ |
| 207 | + else failed++ |
| 208 | + } |
| 209 | +} finally { |
| 210 | + await browser.close() |
| 211 | +} |
| 212 | + |
| 213 | +if (slugs.length > 1) { |
| 214 | + console.log(`Results: ${succeeded} succeeded, ${failed} failed out of ${slugs.length} total`) |
| 215 | +} |
| 216 | + |
| 217 | +process.exit(failed > 0 ? 1 : 0) |
0 commit comments