Skip to main content

Page to PDF

Opens a page and saves it as a PDF. Short, and useful as the last step of anything that has to leave a record: an order confirmation, a submitted form, a portal screen that will not look the same tomorrow.

The workflow

StartWebBrowser("https://books.toscrape.com/catalogue/sharp-objects_997/index.html", "newBrowserSession")
WaitForElement("article.product_page", state="visible", timeout=30000)

pdf = WebpageToPDF("C:/Temp/rinkt-examples/product.pdf", format="A4", margin="12mm", printBackground=True, media="print")
WriteLine("Saved {{ pdf }}")

Two seconds, and a 144 KB PDF on disk.

It needs a headless browser

Webpage to PDF requires headless Chrome. No other engine can produce a PDF, and a Chrome with a visible window cannot either — printing is a capability of the headless protocol. Run the workflow headless, or this step fails while every step before it succeeded.

The two settings that matter

printBackground is off by default, and the default is wrong for most of what you will want to capture. A browser printing to paper assumes you want to save ink, so it drops background colours and images — which turns a coloured dashboard, a status banner or a branded document white. Turn it on unless you are genuinely printing.

media chooses which stylesheet renders. print is what a PDF normally wants. Switch to screen only when the page's own print rules hide the thing you are trying to capture, which some applications do to their own navigation and controls.

Beyond those: format sets the paper size, preferCSSPageSize hands that decision to a @page rule in the page's own stylesheet — the right choice for a page that was built to be printed — and scale between 0.1 and 2 fits a wide page onto narrower paper.

Wait for the content, not the page

WaitForElement before the print is not ceremony. A PDF taken while the page is still assembling captures the half-assembled page perfectly, and produces a file that looks plausible until someone opens it. Wait for something that only exists once the page is done — and wait for exactly one of it.