html2poster.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. #!/usr/bin/env node
  2. /**
  3. * html2poster.js — Single-page poster/long-image HTML → PDF converter
  4. *
  5. * Purpose: Convert a fixed-width, dynamic-height HTML poster into a single-page
  6. * vector PDF with zero margins. This script is PURPOSE-BUILT for posters and
  7. * infographics — it does NOT handle multi-page documents, A4 pagination, or
  8. * document-style margins. For those, use html2pdf-next.js.
  9. *
  10. * Usage:
  11. * node html2poster.js poster.html
  12. * node html2poster.js poster.html --output out.pdf
  13. * node html2poster.js poster.html --width 720px
  14. * node html2poster.js poster.html --width 720px --max-height 8000
  15. *
  16. * What it does (in order):
  17. * 1. Load HTML in Playwright
  18. * 2. Force overflow:hidden on .poster/.page containers (clip decorative overflow)
  19. * 3. Inject @page { margin: 0 } (override any existing margin)
  20. * 4. Ensure html/body have margin:0, padding:0, matching background
  21. * 5. Measure .poster scrollHeight (actual content height)
  22. * 6. Generate single-page PDF with exact dimensions
  23. *
  24. * What it does NOT do:
  25. * - No pagination / page breaks
  26. * - No A4 fallback
  27. * - No margin injection (always zero)
  28. * - No cover adaptation
  29. * - No pdf-lib post-processing
  30. * - No continuous-canvas detection
  31. * - No vertical overflow expansion (posters WANT overflow:hidden)
  32. */
  33. const fs = require('fs');
  34. const path = require('path');
  35. const { execSync, spawnSync } = require('child_process');
  36. // ── Playwright resolution ──
  37. function loadPlaywright() {
  38. for (const name of ['playwright', 'playwright-core']) {
  39. try { return require(name); } catch (_) {}
  40. }
  41. // Node never searches npm's global dir, and when node itself was installed
  42. // into a private prefix, playwright is usually installed right next to it.
  43. // Resolve both by hand instead of reporting "not installed".
  44. const Module = require('module');
  45. const roots = new Set();
  46. if (process.env.PLAYWRIGHT_PATH) roots.add(process.env.PLAYWRIGHT_PATH);
  47. if (process.env.NODE_PATH) {
  48. process.env.NODE_PATH.split(path.delimiter).filter(Boolean).forEach(p => roots.add(p));
  49. }
  50. // <prefix>/bin/node -> <prefix>/node_modules
  51. roots.add(path.join(path.dirname(process.execPath), '..', 'node_modules'));
  52. try {
  53. const g = execSync('npm root -g', { stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim();
  54. if (g) roots.add(g);
  55. } catch (_) {}
  56. for (const base of roots) {
  57. for (const name of ['playwright', 'playwright-core']) {
  58. const dir = path.join(base, name);
  59. if (!fs.existsSync(path.join(dir, 'package.json'))) continue;
  60. // Require by absolute path — createRequire() would still walk the
  61. // node_modules chain and miss roots not named node_modules.
  62. try { return Module.createRequire(__filename)(dir); } catch (_) {}
  63. }
  64. }
  65. return null;
  66. }
  67. // ── Chromium resolution (shared logic with html2pdf-next.js) ──
  68. function resolveChromium(chromiumObj) {
  69. let exe;
  70. try { exe = chromiumObj.executablePath(); } catch (_) { exe = null; }
  71. if (exe && fs.existsSync(exe)) return { status: 'ok', executablePath: exe };
  72. const candidates = [
  73. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
  74. '/Applications/Chromium.app/Contents/MacOS/Chromium',
  75. '/usr/bin/chromium-browser', '/usr/bin/chromium', '/usr/bin/google-chrome',
  76. ];
  77. if (process.env.PLAYWRIGHT_CHROMIUM_PATH) candidates.unshift(process.env.PLAYWRIGHT_CHROMIUM_PATH);
  78. for (const c of candidates) {
  79. if (fs.existsSync(c)) return { status: 'fallback', executablePath: c };
  80. }
  81. return { status: 'missing', executablePath: exe || '' };
  82. }
  83. // ── CLI parsing ──
  84. function parseArgs(argv) {
  85. const tokens = argv.slice(2);
  86. let input = null, output = null, width = '720px', maxHeight = 16000;
  87. for (let i = 0; i < tokens.length; i++) {
  88. const t = tokens[i];
  89. if (t === '--output' || t === '-o') output = tokens[++i];
  90. else if (t === '--width') width = tokens[++i];
  91. else if (t === '--max-height') maxHeight = parseInt(tokens[++i], 10);
  92. else if (t === '--help' || t === '-h') {
  93. console.log(`
  94. Usage: node html2poster.js <input.html> [options]
  95. Options:
  96. --output, -o Output PDF path (default: input with .pdf extension)
  97. --width Poster width (default: 720px)
  98. --max-height Maximum allowed height in px (default: 16000, safety limit)
  99. -h, --help Show this help
  100. `);
  101. process.exit(0);
  102. }
  103. else if (!input) input = t;
  104. else if (!output) output = t;
  105. }
  106. if (!input) {
  107. console.error('Error: No input HTML file specified.');
  108. process.exit(1);
  109. }
  110. if (!output) {
  111. output = input.replace(/\.html?$/i, '.pdf');
  112. if (output === input) output = input + '.pdf';
  113. }
  114. return { input, output, width, maxHeight };
  115. }
  116. // ── Main ──
  117. async function main() {
  118. const { input, output, width, maxHeight } = parseArgs(process.argv);
  119. const absIn = path.resolve(input);
  120. const absOut = path.resolve(output);
  121. if (!fs.existsSync(absIn)) {
  122. console.error(`Error: File not found: ${absIn}`);
  123. process.exit(1);
  124. }
  125. console.log(`\n🖼 html2poster — Single-page poster PDF generator`);
  126. console.log(` Input: ${absIn}`);
  127. console.log(` Output: ${absOut}`);
  128. console.log(` Width: ${width}`);
  129. // Load Playwright
  130. const playwright = loadPlaywright();
  131. if (!playwright) {
  132. console.error('Error: playwright or playwright-core not installed.');
  133. console.error(` Searched: require paths, PLAYWRIGHT_PATH, NODE_PATH,`);
  134. console.error(` ${path.join(path.dirname(process.execPath), '..', 'node_modules')}, npm root -g`);
  135. process.exit(1);
  136. }
  137. const { chromium } = playwright;
  138. const bInfo = resolveChromium(chromium);
  139. if (bInfo.status === 'missing') {
  140. console.error('Error: No Chromium found. Run: npx playwright install chromium');
  141. process.exit(1);
  142. }
  143. if (bInfo.status === 'fallback') {
  144. console.log(` ⚠ Using fallback Chromium: ${bInfo.executablePath}`);
  145. }
  146. // Launch browser
  147. const launchOpts = { headless: true };
  148. if (bInfo.status === 'fallback') launchOpts.executablePath = bInfo.executablePath;
  149. const browser = await chromium.launch(launchOpts);
  150. try {
  151. // Use a wide viewport so content doesn't wrap unexpectedly
  152. const widthPx = parseInt(width, 10) || 720;
  153. const page = await browser.newPage({ viewport: { width: widthPx, height: 1200 } });
  154. await page.goto('file://' + absIn, { waitUntil: 'networkidle' });
  155. console.log(`\n ✓ HTML loaded`);
  156. // ── Step 1: Force overflow:hidden on page containers ──
  157. // Decorative elements with negative offsets or width>100% inflate scrollWidth,
  158. // causing Playwright to shrink content to fit. overflow:hidden clips them.
  159. const overflowFixed = await page.evaluate(() => {
  160. const selectors = ['.poster', '.page', '#poster', '#page'];
  161. let fixed = 0;
  162. for (const sel of selectors) {
  163. const el = document.querySelector(sel);
  164. if (!el) continue;
  165. const computed = getComputedStyle(el);
  166. if (computed.overflow !== 'hidden') {
  167. el.style.overflow = 'hidden';
  168. fixed++;
  169. }
  170. }
  171. return fixed;
  172. });
  173. if (overflowFixed > 0) {
  174. console.log(` ✓ Added overflow:hidden to ${overflowFixed} container(s)`);
  175. }
  176. // ── Step 2: Inject @page { margin: 0 } — override any existing @page rule ──
  177. await page.evaluate(() => {
  178. const s = document.createElement('style');
  179. // Use !important-equivalent: place at end so it wins cascade
  180. s.textContent = `@page { margin: 0 !important; size: auto; }`;
  181. document.head.appendChild(s);
  182. });
  183. // ── Step 3: Ensure html/body have zero margin/padding ──
  184. const bgSync = await page.evaluate(() => {
  185. const html = document.documentElement;
  186. const body = document.body;
  187. html.style.margin = '0';
  188. html.style.padding = '0';
  189. body.style.margin = '0';
  190. body.style.padding = '0';
  191. // Sync body background with poster background to avoid color gaps
  192. const poster = document.querySelector('.poster') || document.querySelector('.page');
  193. if (poster) {
  194. const posterBg = getComputedStyle(poster).backgroundColor;
  195. if (posterBg && posterBg !== 'rgba(0, 0, 0, 0)' && posterBg !== 'transparent') {
  196. body.style.backgroundColor = posterBg;
  197. html.style.backgroundColor = posterBg;
  198. return posterBg;
  199. }
  200. }
  201. return null;
  202. });
  203. if (bgSync) {
  204. console.log(` ✓ Synced body background: ${bgSync}`);
  205. }
  206. // ── Step 4: Measure actual content height ──
  207. const measurement = await page.evaluate(() => {
  208. const poster = document.querySelector('.poster') || document.querySelector('.page') || document.body;
  209. return {
  210. scrollHeight: poster.scrollHeight,
  211. scrollWidth: poster.scrollWidth,
  212. offsetWidth: poster.offsetWidth,
  213. selector: poster.className ? '.' + poster.className.split(' ')[0] : poster.tagName,
  214. };
  215. });
  216. console.log(` ✓ Measured: ${measurement.selector} = ${measurement.scrollWidth}×${measurement.scrollHeight}px`);
  217. if (measurement.scrollWidth > widthPx + 2) {
  218. console.log(` ⚠ WARNING: scrollWidth (${measurement.scrollWidth}px) > width (${widthPx}px)`);
  219. console.log(` Decorative elements may still overflow. Check for position:absolute elements with negative offsets.`);
  220. }
  221. let contentHeight = measurement.scrollHeight;
  222. if (contentHeight > maxHeight) {
  223. console.log(` ⚠ Content height ${contentHeight}px exceeds max ${maxHeight}px, clamping.`);
  224. contentHeight = maxHeight;
  225. }
  226. if (contentHeight < 100) {
  227. console.log(` ⚠ Content height ${contentHeight}px seems too small, using 960px fallback.`);
  228. contentHeight = 960;
  229. }
  230. // ── Step 5: Generate PDF ──
  231. console.log(`\n 📄 Generating PDF: ${width} × ${contentHeight}px`);
  232. await page.pdf({
  233. path: absOut,
  234. width: width,
  235. height: contentHeight + 'px',
  236. printBackground: true,
  237. margin: { top: '0', right: '0', bottom: '0', left: '0' },
  238. });
  239. console.log(`\n ✅ Done: ${absOut}`);
  240. console.log(` Size: ${(fs.statSync(absOut).size / 1024).toFixed(1)} KB`);
  241. } finally {
  242. await browser.close();
  243. }
  244. }
  245. main().catch(err => {
  246. console.error(`\n✗ Fatal: ${err.message}`);
  247. process.exit(1);
  248. });