今日已更新 340 条资讯 | 累计 26752 条内容
关于我们

Converting a JavaScript-Rendered Web Page to PDF

PetrDev 2026年08月01日 17:58 0 次阅读 来源:Dev.to

If you've ever tried to turn a modern web page into a PDF programmatically, you've probably hit the wall: the file comes out blank, half-empty, or frozen on a loading spinner. The page looks perfect in the browser, so what gives? The answer is timing. Most PDF approaches grab the HTML before the JavaScript has rendered the content. On a server-rendered page that's fine — the markup is already there. On a React/Vue/Angular app, the server sends an near-empty shell and the browser builds the DOM afterward. Capture too early and you save the shell. Here's how to do it properly. Why the naive approaches fail wkhtmltopdf is the classic Google answer. It's fast and it's been around forever, but it uses an ancient WebKit build with effectively no modern JavaScript support. For a static page it's fine. For anything client-rendered, it captures the empty state. Browser window.print() / Ctrl+P works because it is a real browser — but it's manual, single-page, and impossible to automate cleanly at scale. Hitting the raw HTML with an HTTP client (axios/fetch then pipe to a PDF lib) has the same fatal flaw as wkhtmltopdf : no JS execution, no rendered content. What you actually need is a real browser engine that runs the page's JavaScript, waits for it to settle, and then prints. That's Puppeteer. The Puppeteer approach Puppeteer drives a headless Chromium. It executes the page exactly like a normal Chrome tab, so whatever renders on screen is what you capture. const puppeteer = require ( ' puppeteer ' ); async function pageToPdf ( url , outPath ) { const browser = await puppeteer . launch ({ args : [ ' --no-sandbox ' , ' --disable-setuid-sandbox ' ], // needed in most containers }); const page = await browser . newPage (); await page . goto ( url , { waitUntil : ' networkidle0 ' , timeout : 60000 }); await page . pdf ({ path : outPath , format : ' A4 ' , printBackground : true , // otherwise CSS backgrounds/colors are dropped margin : { top : ' 20px ' , bottom : ' 20px ' , left

本文内容来源于互联网,版权归原作者所有
查看原文