// Print LAWnB 주석서 TOC pages to PDF, one file per page-level item. // Render with render.py, then run (sandbox must be disabled): // ego-browser nodejs < rendered.js // // CFG = { // task: "unique task space name", // bookUrl: "https://academynext-lawnb-com.libra.cnu.ac.kr/Info/ContentView?sid=_", // rootRegex: "^제2장 계약", // TOC node whose DIRECT children are the 대항목 // groups: [ {key: "2", match: "^제2절"}, {key: "t", match: "^\\[총설\\]$"} ], // tmpDir: "/abs/path/ending/with/slash/", // scratch dir for individual PDFs // waitMs: 4500 // optional; wait after selecting a page // } // Each group = every page-level anchor (href id with exactly two parts) found // anywhere under the matching child
  • , in TOC order. Files are written as // s{key}_{NN}_{label}.pdf (NN = 01.. in TOC order; label = 총설 | 제N조 | 부칙 | [제목] | X) // Files that already exist are skipped, so a crashed or timed-out run can be // started again unchanged. const CFG = __CFG__; const task = await taskSpace(CFG.task); const page = task.page("p1"); const fs = await import("node:fs/promises"); await fs.mkdir(CFG.tmpDir, { recursive: true }); const WAIT = CFG.waitMs || 4500; await page.goto(CFG.bookUrl, { timeout: 30000 }); await page.waitForTimeout(3000); const groups = await page.evaluate((cfg) => { const ownText = (li) => { const a = li.querySelector(':scope > a'); return a ? a.innerText.trim() : [...li.childNodes].filter(n => n.nodeType === 3).map(n => n.textContent.trim()).join(''); }; const root = [...document.querySelectorAll('li')].find(li => new RegExp(cfg.rootRegex).test(ownText(li))); if (!root) return { __error: 'root not found: ' + cfg.rootRegex }; const ol = root.querySelector(':scope > ol, :scope > ul'); const out = {}; for (const li of ol.children) { const t = ownText(li); for (const g of cfg.groups) { if (out[g.key] || !new RegExp(g.match).test(t)) continue; out[g.key] = [...li.querySelectorAll('a')] .filter(x => /showTargetContent\('[^'|]+\|\d+\|R1'\)/.test(x.getAttribute('href') || '')) .map(x => ({ t: x.innerText.trim(), h: x.getAttribute('href') })); } } return out; }, CFG); if (groups.__error) throw new Error(groups.__error); const label = (t) => { if (t === '[총설]') return '총설'; const m = t.match(/^제\d+조(?:의\d+)?/); if (m) return m[0]; if (/^부칙/.test(t)) return '부칙'; const g = t.match(/^\[([^\]:]+)/); return g ? g[1].replace(/\s+/g, '') : 'X'; }; const norm = (s) => s.replace(/\s+/g, '').replace(/[\[\]]/g, ''); let lastTxt = ""; async function printOne(h, title, outPath) { for (let attempt = 1; attempt <= 3; attempt++) { try { if (attempt > 1) { await page.goto(CFG.bookUrl, { timeout: 30000 }); await page.waitForTimeout(3000); } await page.evaluate((h) => { doc.showTargetContent(h.match(/showTargetContent\('([^']+)'\)/)[1]); }, h); await page.waitForTimeout(WAIT + attempt * 1000); // too short a wait prints the previous page await page.click("#pring_set", { label: "인쇄 버튼 클릭" }); await page.waitForTimeout(1500); const btn = await page.evaluate(() => [...document.querySelectorAll('button')] .filter(e => /^인쇄$/.test(e.innerText.trim()) && e.offsetParent) .map(e => { const r = e.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; })); const popupP = page.waitForEvent("popup", { timeout: 15000 + attempt * 5000 }); await page.mouse.click(btn[0].x, btn[0].y, { label: "레이어 인쇄 버튼" }); const p2 = await popupP; // ContentPrintView popup await page.waitForTimeout(2500); const txt = await p2.evaluate(() => document.body.innerText); const titleOk = title === '[총설]' ? txt.includes('[총설]') : norm(txt).includes(norm(title).slice(0, 10)); const ok = titleOk && txt !== lastTxt; // identical text = stale previous page if (!ok && attempt < 3) { console.log(" mismatch/stale, retry", title); await p2.close(); continue; } const r = await p2.cdp("Page.printToPDF", { printBackground: true, preferCSSPageSize: true }); await fs.writeFile(outPath, Buffer.from(r.data, "base64")); lastTxt = txt; console.log(ok ? "saved" : "SAVED-UNVERIFIED", outPath.split('/').pop(), "|", title, "|", (await fs.stat(outPath)).size); await p2.close(); return true; } catch (e) { console.log(" retry", title, attempt, String(e).slice(0, 80)); } } console.log("FAIL", title); return false; } for (const g of CFG.groups) { const items = groups[g.key]; if (!items) { console.log("NO MATCH for group", g.key, g.match); continue; } console.log("GROUP", g.key, items.length); let n = 0; for (const it of items) { n++; const pth = CFG.tmpDir + "s" + g.key + "_" + String(n).padStart(2, '0') + "_" + label(it.t) + ".pdf"; try { await fs.stat(pth); continue; } catch (e) { /* not there yet */ } await printOne(it.h, it.t, pth); } } console.log(await task.finish({ keep: [] }));