How to Convert HTML to PDF: Browser and Code Examples

by .

To convert HTML to PDF once, open the page in a browser, choose Print and select a PDF destination. For repeated exports, use an HTML rendering tool such as Puppeteer or WeasyPrint. Renaming an .html file to .pdf does not convert its contents.

The right method depends on the document. A receipt that is already visible in your browser needs a different workflow from hundreds of reports generated each night. This guide explains how to convert HTML to PDF, prepare print styles and check the resulting file before sharing it.

Choice between a one-off browser PDF export, repeated browser automation and document rendering
Choose a conversion method for the number and type of documents you need.

How to convert HTML to PDF in a browser

Open the HTML file or webpage and let its useful content finish loading. Use the browser’s Print command. In the destination or printer list, choose the option that saves a PDF. The exact wording depends on the browser and operating system; you are looking for a file destination rather than a physical printer. The College of Charleston’s Chrome-to-PDF walkthrough illustrates this print-dialog workflow.

Check the preview before saving. Choose a suitable paper size, portrait or landscape orientation, and sensible margins. Inspect the first and last pages. If a second page contains only a footer or one stray line, adjust the layout rather than immediately making all the text smaller.

Background graphics and browser-added headers or footers are separate print settings. Enable backgrounds when they carry information you need. Turn off the browser’s date or address header if it would add clutter. Keep enough contrast for readers who print the PDF in black and white.

Save the file with a meaningful name, then open the saved PDF in a reader. A preview is not the final deliverable. Confirm that the expected text and images are present, and that you saved the intended page rather than a sign-in screen, loading message or empty application shell.

Choose the method for your document

Practical HTML-to-PDF options
Method Useful for Check before choosing
Browser Print A small number of pages you can inspect Print settings and visible loaded content
Puppeteer Repeated exports using a browser engine Application readiness and required browser resources
WeasyPrint Document-oriented HTML and CSS workflows Supported CSS and system dependencies
Prince Specialist paged-document production Licensing and the features your layout needs

Do not choose solely from a screenshot of a short sample. Try your longest table, a page containing a large image and a document with long names. An engine that handles one neat page may need different CSS for the report you actually produce.

Prince is a paged-document alternative that accepts HTML input and writes a PDF file. Review its licensing before adopting it for your use. The point is to choose a renderer with the capabilities your documents need, then test it with representative content.

Prepare the HTML and CSS for PDF output

A screen can scroll indefinitely. A sheet of paper has an edge. Print CSS lets you remove interface controls, choose page margins and keep short content groups together where possible. MIT’s universal-design lecture includes print CSS examples using @page and @media print. Keep the document’s headings and reading order meaningful before adjusting its appearance.

The following self-contained example includes screen and print rules. Save it as report.html. The navigation is useful on screen but hidden in print. The page rule requests A4 paper with margins. Actual output still depends on the renderer and the print settings you select.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Workshop report</title>
  <style>
    body { font: 16px/1.5 sans-serif; margin: 2rem; color: #172b3a; }
    main { max-width: 48rem; margin-inline: auto; }
    .card { border: 1px solid #8899aa; padding: 1rem; }
    img { max-width: 100%; height: auto; }
    @page { size: A4; margin: 18mm; }
    @media print {
      nav { display: none; }
      body { margin: 0; font-size: 11pt; color: #000; }
      main { max-width: none; }
      .card { break-inside: avoid; }
    }
  </style>
</head>
<body>
  <nav aria-label="Page"><a href="#report">Read report</a></nav>
  <main id="report">
    <h1>Workshop report</h1>
    <section class="card">
      <h2>Materials</h2>
      <p>Bring a notebook and a pencil.</p>
    </section>
  </main>
</body>
</html>

The card’s break-inside rule asks the renderer to avoid splitting it. It cannot make an arbitrarily long block fit onto one page. When a section is taller than the available page area, allow the content to continue sensibly rather than relying on avoidance rules to perform the impossible.

Keep image widths flexible and preserve their proportions. A fixed-width screenshot that fits your monitor can be clipped on paper. Avoid fixed heights for text containers, too. A longer paragraph or substituted font may need more room than your original sample.

If your stylesheet is separate, make sure the renderer can resolve its address. Our guide to linking CSS to HTML explains the markup connection. A PDF engine cannot apply a stylesheet that it cannot find or is not permitted to fetch.

Screen layout with navigation compared with a printed A4 page using margins and simplified content

Print rules can remove navigation and adapt the document to a paper-sized page.

Convert HTML to PDF with Puppeteer

Puppeteer controls a browser programmatically. Its Page.pdf() method writes a PDF file. This is useful when your export should use browser rendering, including the result of scripts that prepare the page.

Install Puppeteer in a Node.js project, then save the following script as export.mjs. Keep report.html beside it. The script uses a local file URL, opens the page, waits for its images to finish decoding and writes report.pdf. Run it from a directory where you can write that output.

npm install puppeteer
node export.mjs
import puppeteer from 'puppeteer';

const browser = await puppeteer.launch();
try {
  const page = await browser.newPage();
  await page.goto(new URL('./report.html', import.meta.url).href, {
    waitUntil: 'networkidle0',
  });
  await page.evaluate(async () => {
    await Promise.all(Array.from(document.images, async image => {
      await image.decode();
    }));
  });
  await page.pdf({
    path: 'report.pdf',
    printBackground: true,
    preferCSSPageSize: true,
  });
} finally {
  await browser.close();
}

The PDF options request background graphics and give the CSS page size priority. Page.pdf() uses print styling by default. For an interactive application, replace the local file with the intended address and wait for a specific ready condition, such as the completed report element. A quiet network alone does not establish that your business data is ready.

Notice the finally block. It closes the browser even if the export fails. In a service, also set reasonable time and resource limits and report failures clearly. A zero-byte file or a successful HTTP response containing an error page should never be accepted as a finished report.

Convert document HTML with WeasyPrint

WeasyPrint is another option for turning HTML and CSS into a PDF. Install it and its platform dependencies for your operating system before running this small Python example.

from weasyprint import HTML

HTML(filename='report.html').write_pdf('report.pdf')

Using an explicit filename avoids ambiguity about whether a string is a path or a URL. Relative resources in a file-based document can be resolved from that document’s location. If you instead create HTML from a string, supply an appropriate base_url when the content depends on relative image or stylesheet addresses.

WeasyPrint is not a replacement for a full browser executing your application. If scripts normally populate a report, create the report’s HTML first or choose a browser-based workflow. Do not hand an empty application shell to a document renderer and expect it to invent the missing content.

Keep untrusted input away from unrestricted file and network access. A conversion service needs limits on where resources can be fetched and how much work a request can trigger. That matters even if your initial demonstration converts only a harmless local page.

Fix common HTML-to-PDF problems

Check the input before changing the converter
Problem Likely area to inspect Useful next step
Images are missing Paths, permissions or loading Resolve resources from the renderer’s location
Content is cut off Fixed widths, heights or overflow Use flexible dimensions and inspect print CSS
Fonts look different Available fonts and load timing Check font access, licensing and substitution
There are blank pages Forced breaks or oversized content Inspect page-break rules and the final content block
The report is empty Authentication or application readiness Inspect the actual document before exporting

Start with the smallest page that still shows the problem. Remove unrelated navigation, then test the troublesome table or image on its own. Once the reduced example works, restore the surrounding content gradually. This is much easier to reason about than changing a dozen print options together.

Use real text when checking alignment and wrapping. A short placeholder can hide a layout failure that appears with an actual customer name. For ordinary text placement, our guide to centering an image in HTML explains how image placement relates to its surrounding box.

Checklist covering loaded resources, readable text, page breaks and final PDF inspection

Inspect the saved PDF, including its text, resources and page boundaries.

Check the PDF as a document

Open the output and search for a distinctive phrase. Try selecting a paragraph. Check important destinations, page order, table headings and the last line of each section. Keeping text as text is usually more useful than flattening every page into a screenshot.

Accessibility needs its own review. The University of Illinois PDF accessibility guidance covers tags, reading order, alternative text and checks before sharing. Selectable text or a tagged-output option alone does not prove the document is accessible. Test the finished document for the requirements that apply to your readers; a good-looking export is only one part of that assessment.

For repeated exports, keep a small set of representative input files and compare results when you update the renderer, fonts or styles. Include empty states and long content as well as the common case. Record the engine version and settings so an unexpected change has a traceable starting point.

Keep the export reproducible

Give the input and output different filenames and keep the HTML source. You may need to correct the document later, and editing a generated PDF is usually a less convenient starting point than fixing the template that produced it. Store the stylesheet with the template so a future export does not silently pick up unrelated design changes.

For automated jobs, create the output in a temporary location first. Check that a non-empty PDF was produced and that the job finished successfully before moving it to the destination another process reads. That prevents a failed conversion from replacing a previously usable report with an incomplete file.

Be explicit about the content date, too. A PDF is a snapshot of what the renderer received. If an underlying page changes tomorrow, yesterday’s exported file will not update itself. Put the relevant reporting period in the document where appropriate, rather than relying only on the filename to explain what the figures describe.

Choose between text and a screenshot deliberately

A screenshot may be enough when the purpose is to record a visual state. It is a poorer substitute for a long document that readers need to search, copy or navigate. Check your actual output: selecting text should select the words in a sensible order, not merely draw a box around one large page image.

Also try a link that matters to the document. Do not assume that every interactive website feature becomes a usable PDF feature. Menus, application buttons and live filters depend on their original environment. Replace essential interactions with clear document content or an ordinary destination the reader can follow.

Questions and self-check

Can I convert HTML to PDF without uploading it?

Yes. A browser can save a page locally, and locally installed rendering tools can write a PDF. Remote images or fonts may still cause network requests, so check the document’s resources as well as the converter.

Will every renderer produce identical pages?

No. Rendering engines, fonts, supported CSS and settings can differ. Test the engine you plan to use, especially for complex layouts and pagination.

Self-check: does changing report.html to report.pdf convert the file?

No. The extension is a name. A rendering process must produce an actual PDF document.

Self-check: why can a valid page produce an empty PDF?

The renderer may have received a sign-in screen, an empty shell or content whose scripts have not finished. Inspect the actual input and readiness condition before changing page margins.

Comments are closed.