html2pdf-next.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. #!/usr/bin/env node
  2. /**
  3. * html2pdf-next.js — HTML → PDF converter using Playwright + pdf-lib
  4. *
  5. * Drop-in replacement for html2pdf.js, WITHOUT Paged.js dependency.
  6. * Uses Chromium native @page CSS for pagination + pdf-lib for post-processing.
  7. *
  8. * Usage:
  9. * node html2pdf-next.js input.html
  10. * node html2pdf-next.js input.html --output result.pdf
  11. * node html2pdf-next.js input.html --css extra.css
  12. * node html2pdf-next.js input.html --width 720px --height 960px
  13. * node html2pdf-next.js input.html --direct (same as default now — no Paged.js to skip)
  14. * node html2pdf-next.js input.html --merge a.pdf b.pdf (merge additional PDFs after)
  15. *
  16. * Architecture:
  17. * 1. Playwright renders HTML → raw PDF via Chromium's native print engine
  18. * 2. Pre-render hooks: Mermaid, KaTeX, oversized element fixes
  19. * 3. Post-render: pdf-lib for merge, metadata, page count extraction
  20. * 4. No Paged.js, no paged.polyfill.js — CSS @page handles pagination natively
  21. */
  22. const fs = require('fs');
  23. const path = require('path');
  24. const { execSync, spawnSync } = require('child_process');
  25. const sleep = ms => new Promise(r => setTimeout(r, ms));
  26. // ═══════════════════════════════════════════════════════════════════
  27. // Playwright / Chromium resolution (self-contained, no external helper)
  28. // ═══════════════════════════════════════════════════════════════════
  29. function loadPlaywright() {
  30. // Try direct require first
  31. try { return require('playwright'); } catch (_) {}
  32. // Search common global paths
  33. const Module = require('module');
  34. const roots = new Set();
  35. if (process.env.PLAYWRIGHT_PATH) roots.add(process.env.PLAYWRIGHT_PATH);
  36. if (process.env.NODE_PATH) {
  37. process.env.NODE_PATH.split(path.delimiter).filter(Boolean).forEach(p => roots.add(p));
  38. }
  39. try {
  40. const g = execSync('npm root -g', { stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim();
  41. if (g) roots.add(g);
  42. } catch (_) {}
  43. for (const base of roots) {
  44. const pkg = path.join(base, 'playwright', 'package.json');
  45. if (!fs.existsSync(pkg)) continue;
  46. try { return Module.createRequire(pkg)('playwright'); } catch (_) {}
  47. }
  48. throw new Error('Playwright not found. Install: npm install -g playwright');
  49. }
  50. function loadPdfLib() {
  51. try { return require('pdf-lib'); } catch (_) {}
  52. const Module = require('module');
  53. try {
  54. const g = execSync('npm root -g', { stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim();
  55. const pkg = path.join(g, 'pdf-lib', 'package.json');
  56. if (fs.existsSync(pkg)) return Module.createRequire(pkg)('pdf-lib');
  57. } catch (_) {}
  58. throw new Error('pdf-lib not found. Install: npm install -g pdf-lib');
  59. }
  60. function resolveChromium(chromiumObj, allowInstall = false) {
  61. let exe;
  62. try { exe = chromiumObj.executablePath(); } catch (_) { exe = null; }
  63. if (exe && fs.existsSync(exe)) {
  64. return { status: 'ok', executablePath: exe };
  65. }
  66. // Try system Chrome/Chromium
  67. const candidates = [
  68. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
  69. '/Applications/Chromium.app/Contents/MacOS/Chromium',
  70. '/usr/bin/chromium-browser', '/usr/bin/chromium', '/usr/bin/google-chrome',
  71. ];
  72. if (process.env.PLAYWRIGHT_CHROMIUM_PATH) candidates.unshift(process.env.PLAYWRIGHT_CHROMIUM_PATH);
  73. for (const c of candidates) {
  74. if (fs.existsSync(c)) return { status: 'fallback', executablePath: c };
  75. }
  76. if (allowInstall) {
  77. const r = spawnSync('npx', ['playwright', 'install', 'chromium'], { stdio: 'inherit', shell: true });
  78. if (r.status === 0) {
  79. try { exe = chromiumObj.executablePath(); } catch (_) {}
  80. if (exe && fs.existsSync(exe)) return { status: 'installed', executablePath: exe };
  81. }
  82. }
  83. return { status: 'missing', executablePath: exe || '' };
  84. }
  85. // ═══════════════════════════════════════════════════════════════════
  86. // CLI
  87. // ═══════════════════════════════════════════════════════════════════
  88. function cli() {
  89. const tokens = process.argv.slice(2);
  90. if (!tokens.length || tokens[0] === '-h' || tokens[0] === '--help') {
  91. console.log(`
  92. Usage: node html2pdf-next.js <input.html> [options]
  93. Options:
  94. --output, -o <file> Output PDF path (default: <input>.pdf)
  95. --css <file> Inject extra stylesheet
  96. --width <px> Custom page width (e.g. 720px)
  97. --height <px> Custom page height (e.g. 960px)
  98. --direct (no-op, kept for backward compat — always direct now)
  99. --merge <files...> Append additional PDF files after conversion
  100. --title <text> Set PDF document title metadata
  101. --help, -h Show help
  102. `);
  103. process.exit(0);
  104. }
  105. const inputFile = tokens[0];
  106. let outputFile = null, customCSS = null, width = null, height = null;
  107. let mergeFiles = [], title = null;
  108. for (let i = 1; i < tokens.length; i++) {
  109. const t = tokens[i];
  110. if (t === '--output' || t === '-o') outputFile = tokens[++i];
  111. else if (t === '--css') customCSS = tokens[++i];
  112. else if (t === '--width') width = tokens[++i];
  113. else if (t === '--height') height = tokens[++i];
  114. else if (t === '--direct') { /* no-op, always direct */ }
  115. else if (t === '--title') title = tokens[++i];
  116. else if (t === '--merge') {
  117. while (i + 1 < tokens.length && !tokens[i + 1].startsWith('--')) {
  118. mergeFiles.push(tokens[++i]);
  119. }
  120. }
  121. }
  122. if (!outputFile) {
  123. const p = path.parse(inputFile);
  124. outputFile = path.join(p.dir || '.', p.name + '.pdf');
  125. }
  126. return { inputFile, outputFile, customCSS, width, height, mergeFiles, title };
  127. }
  128. // ═══════════════════════════════════════════════════════════════════
  129. // Helpers
  130. // ═══════════════════════════════════════════════════════════════════
  131. function prettyBytes(n) {
  132. const units = ['B', 'KB', 'MB', 'GB'];
  133. let u = 0;
  134. while (n >= 1024 && u < units.length - 1) { n /= 1024; u++; }
  135. return `${n.toFixed(1)} ${units[u]}`;
  136. }
  137. // ═══════════════════════════════════════════════════════════════════
  138. // Pre-render hooks (run in browser context before PDF export)
  139. // ═══════════════════════════════════════════════════════════════════
  140. async function preRenderHooks(page) {
  141. const warnings = [];
  142. // 1. Wait for Mermaid diagrams
  143. const hasMermaid = await page.evaluate(() => document.querySelectorAll('.mermaid').length > 0);
  144. if (hasMermaid) {
  145. console.log(' ⏳ Waiting for Mermaid diagrams...');
  146. try {
  147. await page.waitForFunction(() => {
  148. for (const m of document.querySelectorAll('.mermaid'))
  149. if (!m.querySelector('svg') && !m.getAttribute('data-processed')) return false;
  150. return true;
  151. }, { timeout: 30000 });
  152. await sleep(2000);
  153. console.log(' ✓ Mermaid rendered');
  154. } catch (_) {
  155. warnings.push('Mermaid rendering timed out (30s)');
  156. }
  157. }
  158. // 2. Trigger KaTeX math rendering
  159. const katexStatus = await page.evaluate(() => ({
  160. lib: typeof renderMathInElement === 'function' || typeof katex !== 'undefined',
  161. rendered: document.querySelectorAll('.katex').length > 0,
  162. raw: /\$[^$]+\$|\$\$[^$]+\$\$|\\\(.*?\\\)|\\\[.*?\\\]/.test(document.body.innerText),
  163. }));
  164. // Auto-inject KaTeX CDN if raw math detected but library not loaded
  165. if (!katexStatus.lib && katexStatus.raw && !katexStatus.rendered) {
  166. console.log(' ⏳ Auto-injecting KaTeX CDN (math formulas detected but KaTeX not loaded)...');
  167. await page.addStyleTag({ url: 'https://cdn.jsdelivr.net/npm/katex@0.16.22/dist/katex.min.css' });
  168. await page.addScriptTag({ url: 'https://cdn.jsdelivr.net/npm/katex@0.16.22/dist/katex.min.js' });
  169. await page.addScriptTag({ url: 'https://cdn.jsdelivr.net/npm/katex@0.16.22/dist/contrib/auto-render.min.js' });
  170. await sleep(2000); // Wait for CDN scripts to load
  171. // Re-check
  172. const recheckLib = await page.evaluate(() => typeof renderMathInElement === 'function');
  173. if (recheckLib) {
  174. console.log(' ✓ KaTeX CDN loaded successfully');
  175. } else {
  176. console.log(' ⚠ KaTeX CDN failed to load — math will render as raw text');
  177. warnings.push('KaTeX CDN injection failed; math formulas may appear as raw LaTeX code');
  178. }
  179. }
  180. // Re-evaluate after potential CDN injection
  181. const katexReady = await page.evaluate(() => ({
  182. lib: typeof renderMathInElement === 'function' || typeof katex !== 'undefined',
  183. rendered: document.querySelectorAll('.katex').length > 0,
  184. raw: /\$[^$]+\$|\$\$[^$]+\$\$|\\\(.*?\\\)|\\\[.*?\\\]/.test(document.body.innerText),
  185. }));
  186. if (katexReady.lib && !katexReady.rendered && katexReady.raw) {
  187. console.log(' ⏳ Triggering KaTeX rendering...');
  188. await page.evaluate(() => {
  189. if (typeof renderMathInElement === 'function')
  190. renderMathInElement(document.body, {
  191. delimiters: [
  192. { left: '$$', right: '$$', display: true },
  193. { left: '$', right: '$', display: false },
  194. { left: '\\(', right: '\\)', display: false },
  195. { left: '\\[', right: '\\]', display: true },
  196. ],
  197. throwOnError: false,
  198. });
  199. });
  200. await sleep(1000);
  201. console.log(' ✓ KaTeX rendered');
  202. } else if (katexReady.rendered) {
  203. await sleep(500); // Font loading settle
  204. }
  205. // 3. Fix oversized elements that prevent page breaks
  206. const nFixed = await page.evaluate(() => {
  207. const LIMIT = 1000;
  208. let n = 0;
  209. document.querySelectorAll(
  210. '[style*="page-break-inside: avoid"],[style*="break-inside: avoid"],' +
  211. '.avoid-break,table,figure,.theorem,.algorithm'
  212. ).forEach(el => {
  213. if (el.getBoundingClientRect().height > LIMIT) {
  214. el.style.pageBreakInside = 'auto';
  215. el.style.breakInside = 'auto';
  216. n++;
  217. }
  218. });
  219. return n;
  220. });
  221. if (nFixed) {
  222. console.log(` ⚠ Fixed ${nFixed} oversized elements (removed break-inside: avoid)`);
  223. }
  224. // 4. Detect overflow (horizontal AND vertical)
  225. const overflows = await page.evaluate(() => {
  226. const out = [];
  227. document.querySelectorAll('pre,table,figure,img,svg,.mermaid,blockquote,.equation').forEach(el => {
  228. const hDiff = el.scrollWidth - el.clientWidth;
  229. const vDiff = el.scrollHeight - el.clientHeight;
  230. if (hDiff > 2 || vDiff > 2) out.push({
  231. tag: el.tagName.toLowerCase(),
  232. cls: el.className || '',
  233. hOverflow: hDiff > 2 ? hDiff : 0,
  234. vOverflow: vDiff > 2 ? vDiff : 0,
  235. preview: (el.textContent || '').slice(0, 50).replace(/\s+/g, ' '),
  236. });
  237. });
  238. return out;
  239. });
  240. if (overflows.length) {
  241. console.log(' ⚠ Overflow detected:');
  242. overflows.forEach(o => {
  243. const parts = [];
  244. if (o.hOverflow) parts.push(`H +${o.hOverflow}px`);
  245. if (o.vOverflow) parts.push(`V +${o.vOverflow}px`);
  246. console.log(` <${o.tag}${o.cls ? '.' + o.cls.split(' ')[0] : ''}> ${parts.join(', ')}`);
  247. });
  248. warnings.push(`${overflows.length} element(s) have overflow`);
  249. }
  250. // 4b. Fix vertical overflow on page-level containers
  251. // When html/body or the main content canvas has a fixed height + overflow:hidden,
  252. // content gets clipped. For documents (html2pdf-next.js), we DON'T expand the
  253. // container to its scrollHeight — that creates an oversized single "page" that
  254. // Playwright splits unevenly. Instead, we remove the fixed height and overflow:hidden
  255. // so content flows naturally and @page CSS handles pagination.
  256. //
  257. // (The old "expand to scrollHeight" logic belongs in html2poster.js where a single
  258. // continuous canvas is the desired output.)
  259. const vOverflowFix = await page.evaluate(() => {
  260. const fixes = [];
  261. // Candidates: html, body, and any direct child of body that acts as a full-page canvas
  262. const candidates = [document.documentElement, document.body];
  263. const bodyChildren = document.body.children;
  264. for (let i = 0; i < bodyChildren.length; i++) {
  265. const child = bodyChildren[i];
  266. // Skip SVG defs, script, style elements
  267. const tag = child.tagName.toLowerCase();
  268. if (tag === 'svg' || tag === 'script' || tag === 'style' || tag === 'link') continue;
  269. candidates.push(child);
  270. // Also check one level deeper (e.g., .canvas > .content)
  271. for (let j = 0; j < child.children.length; j++) {
  272. const grandchild = child.children[j];
  273. const gtag = grandchild.tagName.toLowerCase();
  274. if (gtag === 'svg' || gtag === 'script' || gtag === 'style') continue;
  275. candidates.push(grandchild);
  276. }
  277. }
  278. for (const el of candidates) {
  279. const computed = getComputedStyle(el);
  280. const overflow = computed.overflow || computed.overflowY;
  281. const hasHiddenOverflow = overflow === 'hidden' || overflow === 'clip';
  282. const diff = el.scrollHeight - el.clientHeight;
  283. if (hasHiddenOverflow && diff > 5) {
  284. // This element is clipping content vertically
  285. const tag = el.tagName.toLowerCase();
  286. const id = el.id ? `#${el.id}` : '';
  287. const cls = el.className ? `.${String(el.className).split(' ')[0]}` : '';
  288. const selector = `${tag}${id}${cls}`;
  289. const oldHeight = el.clientHeight;
  290. // Document mode: remove fixed height + overflow:hidden,
  291. // let @page handle natural pagination
  292. el.style.height = 'auto';
  293. el.style.minHeight = 'auto';
  294. el.style.maxHeight = 'none';
  295. el.style.overflow = 'visible';
  296. el.style.overflowY = 'visible';
  297. fixes.push({
  298. selector,
  299. oldHeight,
  300. clipped: diff,
  301. });
  302. }
  303. }
  304. // After fixing containers, re-measure to get the final content height
  305. const finalHeight = Math.max(
  306. document.documentElement.scrollHeight,
  307. document.body.scrollHeight
  308. );
  309. return { fixes, finalHeight };
  310. });
  311. if (vOverflowFix.fixes.length) {
  312. console.log(' ⚠️ Removed fixed height + overflow:hidden — content will paginate naturally:');
  313. vOverflowFix.fixes.forEach(f => {
  314. console.log(` ${f.selector}: was ${f.oldHeight}px with ${f.clipped}px clipped → now auto (content will flow to next page)`);
  315. });
  316. }
  317. // 4c. Convert absolute-bottom elements to document flow
  318. // Elements with `position: absolute; bottom: Npx` inside page containers
  319. // are pinned relative to their containing block. When content paginates
  320. // across multiple @page pages, these elements either overlap with body
  321. // text or land on the wrong page. Fix: convert them to static positioning
  322. // so they participate in normal document flow and paginate naturally.
  323. const absBottomFix = await page.evaluate(() => {
  324. const converted = [];
  325. // Scan inside page-level containers (body children and their children)
  326. const containers = [];
  327. for (let i = 0; i < document.body.children.length; i++) {
  328. const child = document.body.children[i];
  329. const tag = child.tagName.toLowerCase();
  330. if (tag === 'svg' || tag === 'script' || tag === 'style' || tag === 'link') continue;
  331. containers.push(child);
  332. }
  333. for (const container of containers) {
  334. const descendants = container.querySelectorAll('*');
  335. for (const el of descendants) {
  336. const computed = getComputedStyle(el);
  337. if (computed.position === 'absolute' && computed.bottom !== 'auto' && computed.bottom !== '') {
  338. // Check if this element contains visible text (not just decorative)
  339. const hasText = el.textContent && el.textContent.trim().length > 0;
  340. if (!hasText) continue;
  341. const tag = el.tagName.toLowerCase();
  342. const id = el.id ? `#${el.id}` : '';
  343. const cls = el.className ? `.${String(el.className).split(' ')[0]}` : '';
  344. const selector = `${tag}${id}${cls}`;
  345. // Convert to static flow: remove absolute positioning
  346. el.style.position = 'static';
  347. el.style.bottom = 'auto';
  348. el.style.left = 'auto';
  349. el.style.right = 'auto';
  350. // Preserve horizontal padding/margin from the original left/right values
  351. // by keeping any existing padding or margin on the element
  352. converted.push({ selector, bottom: computed.bottom });
  353. }
  354. }
  355. }
  356. return converted;
  357. });
  358. if (absBottomFix.length) {
  359. console.log(' ⚠️ Converted absolute-bottom elements to document flow (prevents overlap on multi-page):');
  360. absBottomFix.forEach(f => {
  361. console.log(` ${f.selector}: was position:absolute;bottom:${f.bottom} → now static (flows with content)`);
  362. });
  363. }
  364. // 5. Inject minimal @page CSS fallback
  365. await page.evaluate(() => {
  366. const styles = Array.from(document.querySelectorAll('style'));
  367. const hasPageRule = styles.some(s => (s.textContent || '').includes('@page'));
  368. if (!hasPageRule) {
  369. const s = document.createElement('style');
  370. s.textContent = `@page { margin: 20mm; }`;
  371. document.head.appendChild(s);
  372. }
  373. });
  374. // 6. Fix full-page cover sections for print
  375. // In screen mode, height:100vh = viewport height. In print mode, 100vh ≠ page height.
  376. // Detect elements using 100vh and convert to print-safe page-filling behavior.
  377. const coverFixed = await page.evaluate(() => {
  378. let fixed = 0;
  379. // Find elements with height: 100vh (inline or computed)
  380. const allEls = document.querySelectorAll('*');
  381. for (const el of allEls) {
  382. const style = el.style;
  383. const computed = getComputedStyle(el);
  384. const isVh = style.height === '100vh' || computed.height === '100vh' ||
  385. style.minHeight === '100vh' || computed.minHeight === '100vh';
  386. // Also detect via class name hints
  387. const isCover = el.classList.contains('cover') || el.classList.contains('cover-page') ||
  388. el.id === 'cover' || el.getAttribute('data-role') === 'cover';
  389. if (isVh || (isCover && el.offsetHeight > 0)) {
  390. // Force the element to fill the print page
  391. el.style.height = '100vh';
  392. el.style.minHeight = '100vh';
  393. el.style.pageBreakAfter = 'always';
  394. el.style.pageBreakInside = 'avoid';
  395. el.style.boxSizing = 'border-box';
  396. el.style.overflow = 'hidden';
  397. fixed++;
  398. }
  399. }
  400. // Inject print-specific CSS to make 100vh work correctly
  401. if (fixed > 0) {
  402. const s = document.createElement('style');
  403. s.textContent = `
  404. @media print {
  405. .cover, .cover-page, [data-role="cover"] {
  406. height: 100vh !important;
  407. min-height: 100vh !important;
  408. page-break-after: always !important;
  409. page-break-inside: avoid !important;
  410. overflow: hidden !important;
  411. }
  412. }
  413. `;
  414. document.head.appendChild(s);
  415. }
  416. return fixed;
  417. });
  418. if (coverFixed) {
  419. console.log(` ✓ Fixed ${coverFixed} full-page cover section(s) for print`);
  420. // Also inject named @page rule for cover with zero margins
  421. await page.evaluate(() => {
  422. const s = document.createElement('style');
  423. s.textContent = `
  424. @page cover-page {
  425. margin: 0 !important;
  426. }
  427. @media print {
  428. .cover, .cover-page, [data-role="cover"] {
  429. page: cover-page;
  430. margin: 0 !important;
  431. padding: 40px !important;
  432. }
  433. }
  434. `;
  435. document.head.appendChild(s);
  436. });
  437. }
  438. return { warnings, contentHeight: vOverflowFix.finalHeight };
  439. }
  440. // ═══════════════════════════════════════════════════════════════════
  441. // Content statistics (post-render, from PDF or page)
  442. // ═══════════════════════════════════════════════════════════════════
  443. async function collectStats(page) {
  444. return page.evaluate(() => {
  445. const body = document.body;
  446. const text = body.innerText || '';
  447. const zhChars = (text.match(/[\u4e00-\u9fa5]/g) || []).length;
  448. const enWords = (text.match(/[a-zA-Z]+/g) || []).length;
  449. return {
  450. wordCount: zhChars + enWords,
  451. figures: document.querySelectorAll('figure,.figure,img').length,
  452. tables: document.querySelectorAll('table').length,
  453. };
  454. });
  455. }
  456. // ═══════════════════════════════════════════════════════════════════
  457. // pdf-lib post-processing: page count, metadata, merge
  458. // ═══════════════════════════════════════════════════════════════════
  459. async function postProcess(pdfPath, options = {}) {
  460. const { PDFDocument } = loadPdfLib();
  461. const pdfBytes = fs.readFileSync(pdfPath);
  462. const doc = await PDFDocument.load(pdfBytes);
  463. // Set metadata
  464. if (options.title) doc.setTitle(options.title);
  465. doc.setProducer('html2pdf-next (Playwright + pdf-lib)');
  466. doc.setCreationDate(new Date());
  467. const pageCount = doc.getPageCount();
  468. // Merge additional PDFs
  469. if (options.mergeFiles && options.mergeFiles.length) {
  470. for (const mf of options.mergeFiles) {
  471. if (!fs.existsSync(mf)) {
  472. console.log(` ⚠ Merge file not found: ${mf}`);
  473. continue;
  474. }
  475. console.log(` 📎 Merging: ${path.basename(mf)}`);
  476. const donorBytes = fs.readFileSync(mf);
  477. const donorDoc = await PDFDocument.load(donorBytes);
  478. const copiedPages = await doc.copyPages(donorDoc, donorDoc.getPageIndices());
  479. copiedPages.forEach(p => doc.addPage(p));
  480. }
  481. }
  482. // Save
  483. const finalBytes = await doc.save();
  484. fs.writeFileSync(pdfPath, finalBytes);
  485. return { pageCount: doc.getPageCount(), originalPages: pageCount };
  486. }
  487. // ═══════════════════════════════════════════════════════════════════
  488. // Main pipeline
  489. // ═══════════════════════════════════════════════════════════════════
  490. async function convert(inputFile, outputFile, customCSS, options = {}) {
  491. const { width, height, mergeFiles, title } = options;
  492. if (!fs.existsSync(inputFile)) {
  493. console.error(`✗ File not found: ${inputFile}`);
  494. process.exit(1);
  495. }
  496. const playwright = loadPlaywright();
  497. const { chromium } = playwright;
  498. // Resolve browser
  499. const canInstall = process.env.PDF_SKIP_BROWSER_INSTALL !== '1';
  500. const bInfo = resolveChromium(chromium, canInstall);
  501. if (bInfo.status === 'missing') {
  502. console.error('\n✗ Chromium not found. Run: npx playwright install chromium\n');
  503. process.exit(2);
  504. }
  505. if (bInfo.status === 'fallback') {
  506. console.log(`⚠ Using fallback Chromium: ${bInfo.executablePath}`);
  507. }
  508. const absIn = path.resolve(inputFile);
  509. const absOut = path.resolve(outputFile);
  510. console.log(`\n🔄 Converting ${path.basename(inputFile)}...`);
  511. console.log(` Engine: Playwright + Chromium native @page (no Paged.js)`);
  512. // Read and optionally inject CSS
  513. let html = fs.readFileSync(absIn, 'utf-8');
  514. if (customCSS) {
  515. if (!fs.existsSync(customCSS)) {
  516. console.error(`✗ CSS file not found: ${customCSS}`);
  517. process.exit(1);
  518. }
  519. const tag = `<style>${fs.readFileSync(customCSS, 'utf-8')}</style>`;
  520. html = html.includes('</head>') ? html.replace('</head>', tag + '\n</head>') : tag + '\n' + html;
  521. // Write modified HTML for Playwright to load
  522. const tmpHtml = absIn + '.tmp.html';
  523. fs.writeFileSync(tmpHtml, html);
  524. // We'll clean up later
  525. }
  526. // Launch browser
  527. let browser;
  528. try {
  529. const opts = { headless: true };
  530. if (bInfo.status === 'fallback') opts.executablePath = bInfo.executablePath;
  531. browser = await chromium.launch(opts);
  532. } catch (err) {
  533. const msg = err.message || '';
  534. if (msg.includes('shared libraries') || msg.includes('.so')) {
  535. console.error('\n✗ Missing system libraries. Run: npx playwright install-deps chromium\n');
  536. } else {
  537. console.error(`\n✗ Browser launch failed: ${msg}\n`);
  538. }
  539. process.exit(1);
  540. }
  541. try {
  542. const page = await browser.newPage();
  543. const loadFile = customCSS ? absIn + '.tmp.html' : absIn;
  544. await page.goto('file://' + loadFile, { waitUntil: 'networkidle' });
  545. // ── Pre-render hooks ──
  546. console.log('\n📋 Pre-render checks:');
  547. const preRenderResult = await preRenderHooks(page);
  548. const warnings = preRenderResult.warnings;
  549. const measuredContentHeight = preRenderResult.contentHeight;
  550. // ── Detect continuous-canvas mode (design_engine.py output) ──
  551. const continuousInfo = await page.evaluate(() => {
  552. const el = document.querySelector('.continuous-canvas');
  553. if (!el) return null;
  554. const root = getComputedStyle(document.documentElement);
  555. return {
  556. width: root.getPropertyValue('--canvas-w').trim() || '720px',
  557. height: root.getPropertyValue('--canvas-h').trim() || '960px',
  558. pages: el.querySelectorAll('.page-section').length,
  559. };
  560. });
  561. if (continuousInfo) {
  562. // Creative PDF: seamless multi-page canvas
  563. console.log(`\n🎨 Continuous canvas: ${continuousInfo.pages} pages @ ${continuousInfo.width} × ${continuousInfo.height}`);
  564. await page.pdf({
  565. path: absOut,
  566. printBackground: true,
  567. margin: { top: 0, right: 0, bottom: 0, left: 0 },
  568. width: continuousInfo.width,
  569. height: continuousInfo.height,
  570. });
  571. } else {
  572. // Standard document
  573. console.log('\n📄 Rendering PDF...');
  574. const pdfOpts = {
  575. path: absOut,
  576. printBackground: true,
  577. preferCSSPageSize: true,
  578. tagged: true,
  579. };
  580. if (width || height) {
  581. if (width) pdfOpts.width = width;
  582. if (height) pdfOpts.height = height;
  583. pdfOpts.margin = { top: 0, right: 0, bottom: 0, left: 0 };
  584. console.log(` Custom size: ${pdfOpts.width || 'auto'} × ${pdfOpts.height || 'auto'}`);
  585. } else {
  586. // No explicit size: check if @page CSS defines a fixed size
  587. const pageSize = await page.evaluate(() => {
  588. const styles = Array.from(document.querySelectorAll('style'));
  589. for (const s of styles) {
  590. const text = s.textContent || '';
  591. const match = text.match(/@page\s*\{[^}]*size:\s*([\d.]+)px\s+([\d.]+)px/);
  592. if (match) return { width: parseFloat(match[1]), height: parseFloat(match[2]) };
  593. }
  594. return null;
  595. });
  596. if (pageSize) {
  597. // @page defines a fixed size — use preferCSSPageSize (already set above).
  598. // Playwright will paginate content at @page height boundaries seamlessly.
  599. // This is correct for both posters (seamless multi-page) and documents.
  600. pdfOpts.margin = { top: 0, right: 0, bottom: 0, left: 0 };
  601. console.log(` @page size: ${pageSize.width}px × ${pageSize.height}px`);
  602. if (measuredContentHeight && measuredContentHeight > pageSize.height + 5) {
  603. const estPages = Math.ceil(measuredContentHeight / pageSize.height);
  604. console.log(` Content height: ${measuredContentHeight}px → ~${estPages} pages`);
  605. }
  606. } else {
  607. pdfOpts.format = 'A4';
  608. }
  609. }
  610. await page.pdf(pdfOpts);
  611. }
  612. // Collect content stats from the page
  613. const stats = await collectStats(page);
  614. // ── pdf-lib post-processing ──
  615. console.log('\n🔧 Post-processing (pdf-lib):');
  616. const postResult = await postProcess(absOut, { mergeFiles, title });
  617. // Clean up temp HTML
  618. const tmpHtml = absIn + '.tmp.html';
  619. if (fs.existsSync(tmpHtml)) fs.unlinkSync(tmpHtml);
  620. // ── Report ──
  621. const sz = fs.statSync(absOut).size;
  622. console.log('\n' + '═'.repeat(40));
  623. console.log(' PDF Generated Successfully');
  624. console.log('═'.repeat(40));
  625. console.log(` File: ${path.basename(absOut)}`);
  626. console.log(` Pages: ${postResult.pageCount}`);
  627. console.log(` Size: ${prettyBytes(sz)}`);
  628. console.log(` Words: ~${stats.wordCount.toLocaleString()}`);
  629. console.log(` Assets: ${stats.figures} figures, ${stats.tables} tables`);
  630. console.log(` Engine: Playwright (no Paged.js)`);
  631. console.log(` Path: ${absOut}`);
  632. if (mergeFiles && mergeFiles.length && postResult.pageCount > postResult.originalPages) {
  633. console.log(` Merged: +${postResult.pageCount - postResult.originalPages} pages from ${mergeFiles.length} file(s)`);
  634. }
  635. if (warnings.length) {
  636. console.log('\n⚠ Warnings:');
  637. warnings.forEach(w => console.log(` · ${w}`));
  638. }
  639. // Anomaly detection
  640. if (postResult.pageCount > 1 && stats.wordCount > 0) {
  641. const avgWordsPerPage = stats.wordCount / postResult.pageCount;
  642. if (avgWordsPerPage < 30) {
  643. console.log(`\n⚠ Low content density: ~${Math.round(avgWordsPerPage)} words/page (expected 100+)`);
  644. }
  645. }
  646. } catch (err) {
  647. console.error('\n✗ Conversion failed:', err.message);
  648. process.exit(1);
  649. } finally {
  650. await browser.close();
  651. }
  652. }
  653. // ═══════════════════════════════════════════════════════════════════
  654. // Entry
  655. // ═══════════════════════════════════════════════════════════════════
  656. (async () => {
  657. try {
  658. const args = cli();
  659. await convert(args.inputFile, args.outputFile, args.customCSS, {
  660. width: args.width,
  661. height: args.height,
  662. mergeFiles: args.mergeFiles,
  663. title: args.title,
  664. });
  665. } catch (err) {
  666. console.error('Error:', err.message);
  667. process.exit(1);
  668. }
  669. })();