May 9, 2026

HTML to PDF in 2026: All Methods Compared with Code

HTML to PDFcomparisonwkhtmltopdfPuppeteerPDF API

Converting HTML to PDF is a solved problem — in the sense that many tools exist. Choosing the right one for your use case is not trivial, because each method makes different trade-offs on rendering fidelity, CSS support, operational complexity, and cost.

This article covers every major HTML to PDF method available in 2026, with honest pros, cons, and real code for each approach.

For a focused comparison of Puppeteer specifically against a managed API, see Puppeteer vs PDF API. For CSS tips that apply across all Chromium-based methods, see HTML to PDF CSS Tips.

The Methods at a Glance

Method Engine CSS Support Operational Complexity Self-Hosted
Browser print dialog Your browser Browser-dependent None (manual) —
wkhtmltopdf QtWebKit (archived) Different from current browsers Low Yes
Puppeteer / Playwright Chromium Depends on the installed version High Yes
WeasyPrint Python document renderer Document CSS implemented separately Low–Medium Yes
Gotenberg Chromium + LibreOffice Depends on the installed version Medium Yes
Managed PDF API Service-dependent Depends on the service and plan Very Low No

1. Browser Print Dialog

The simplest method: window.print() in JavaScript opens the browser's native print dialog, letting the user save as PDF.

// Trigger print dialog
window.print();

// Or add a print button
document.getElementById('print-btn').addEventListener('click', () => {
  window.print();
});

Pair with CSS @media print rules to control layout:

@media print {
  .no-print { display: none; }
  body { font-size: 12pt; }
  @page { margin: 20mm; size: A4; }
}

Pros:

  • Zero setup, zero cost
  • Uses the reader's browser rendering engine
  • No server-side code required

Cons:

  • User must manually save as PDF — not automatable
  • Print dialog appearance varies by browser and OS
  • Page breaks are hard to control reliably
  • Headers, footers, and multi-page layout are difficult
  • Cannot be triggered silently from a server

Best for: Developer tools, internal dashboards where a "save as PDF" button is sufficient and automation is not needed.

2. wkhtmltopdf

A command-line tool based on the QtWebKit rendering engine. It was the dominant solution for server-side HTML to PDF conversion for many years.

# Install (Debian/Ubuntu)
sudo apt-get install wkhtmltopdf

# Basic conversion
wkhtmltopdf input.html output.pdf

# With options
wkhtmltopdf \
  --page-size A4 \
  --margin-top 20mm \
  --margin-bottom 20mm \
  --margin-left 15mm \
  --margin-right 15mm \
  --encoding utf-8 \
  invoice.html invoice.pdf

# From a URL
wkhtmltopdf https://example.com page.pdf
# Python wrapper
import subprocess

def html_to_pdf(html_path: str, output_path: str) -> None:
    subprocess.run([
        'wkhtmltopdf',
        '--page-size', 'A4',
        '--margin-top', '20mm',
        '--margin-bottom', '20mm',
        html_path,
        output_path,
    ], check=True)

Pros:

  • Converts from the CLI without separately managing a Chromium browser
  • Simple CLI interface
  • Mature and widely documented

Cons:

  • The repository is archived — review the maintenance implications before new adoption
  • QtWebKit differs from current browsers in CSS and JavaScript behavior
  • Test existing Grid and Flexbox templates in actual output
  • JavaScript is supported, but current browser code is not guaranteed to run unchanged
  • CJK output requires suitable font configuration
  • Review migration options for new projects

Best for: Legacy systems already using wkhtmltopdf that are not yet migrated. For migration guidance, see the wkhtmltopdf migration guide.

3. Puppeteer (Node.js)

Puppeteer is a Node.js library that controls a headless Chromium instance. It was originally built for browser automation and testing; PDF generation is one of its features.

const puppeteer = require('puppeteer');

async function generatePdf(html) {
  const browser = await puppeteer.launch({ headless: true });

  const page = await browser.newPage();
  await page.setContent(html, { waitUntil: 'networkidle0' });

  const pdf = await page.pdf({
    format: 'A4',
    margin: { top: '20mm', bottom: '20mm', left: '15mm', right: '15mm' },
    printBackground: true,
  });

  await browser.close();
  return pdf;
}

Pros:

  • Uses the CSS features of the Chromium version you run, including Grid, Flexbox, and custom properties
  • Can run JavaScript before generating the PDF
  • page.pdf() supports paper, margin, and background options

Cons:

  • Requires Chromium installation and version management
  • Memory use and startup time depend on the page and runtime, so measure your workload
  • Concurrent use requires browser and page lifecycle management
  • Not purpose-built for PDF generation

Best for: Low-to-medium volume PDF generation where you are already using Puppeteer for browser testing, or where you need page.evaluate() to run JavaScript before export.

4. Playwright (Node.js, Python, .NET, Java)

Playwright is Microsoft's browser automation library. It can drive Chromium, Firefox, and WebKit, while page.pdf() uses headless Chromium. Output also depends on the browser version and PDF options.

// Node.js
const { chromium } = require('playwright');

async function generatePdf(html) {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();

  await page.setContent(html, { waitUntil: 'networkidle' });
  const pdf = await page.pdf({
    format: 'A4',
    margin: { top: '20mm', bottom: '20mm', left: '15mm', right: '15mm' },
    printBackground: true,
  });

  await browser.close();
  return pdf;
}
# Python
import asyncio
from playwright.async_api import async_playwright

async def generate_pdf(html: str) -> bytes:
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()
        await page.set_content(html, wait_until='networkidle')
        pdf = await page.pdf(
            format='A4',
            margin={'top': '20mm', 'bottom': '20mm',
                    'left': '15mm', 'right': '15mm'},
            print_background=True,
        )
        await browser.close()
        return pdf

Pros:

  • Available for Node.js, Python, .NET, and Java
  • Automates Chromium, Firefox, and WebKit through one API
  • Uses the CSS features of the Chromium version you run

Cons:

  • Like Puppeteer, requires Chromium management and workload-specific performance measurements
  • Install the browser with a command such as playwright install chromium
  • PDF generation is limited to Chromium

Best for: Same situations as Puppeteer, when you prefer Python or .NET, or when you need Firefox/WebKit rendering for testing. If operational problems are the pain point, migrating to a managed API is the higher-ROI move. See the Playwright to PDF API migration guide.

5. WeasyPrint

WeasyPrint is a Python library that converts HTML and CSS to PDF using its own rendering engine (not Chromium). It implements CSS Paged Media features.

# Install
pip install weasyprint

# CLI
weasyprint input.html output.pdf
from weasyprint import HTML, CSS

def generate_pdf(html: str, css: str = None) -> bytes:
    html_doc = HTML(string=html)
    stylesheets = [CSS(string=css)] if css else []
    return html_doc.write_pdf(stylesheets=stylesheets)

WeasyPrint has excellent support for CSS Paged Media features like @page rules, named pages, and running elements:

@page {
  size: A4;
  margin: 20mm;

  @bottom-center {
    content: "Page " counter(page) " of " counter(pages);
  }
}

/* Running header/footer */
.header { position: running(header); }
@page { @top-center { content: element(header); } }

Pros:

  • Excellent CSS Paged Media support (headers, footers, page counters)
  • Python API without Chromium
  • Can be called from Django, Flask, and FastAPI
  • Good for documents with complex multi-page layout

Cons:

  • Does not support JavaScript execution
  • CSS support is not identical to browsers (some modern properties missing)
  • CJK font support requires font installation
  • Rendering can change between versions, so inspect output after upgrades

Best for: Python applications generating structured documents (reports, books, contracts) where CSS Paged Media features are important and JavaScript rendering is not needed.

6. Gotenberg

Gotenberg is an open-source Docker service that exposes a REST API for document conversion with Chromium and LibreOffice.

# Start Gotenberg with Docker
docker run --rm -p 3000:3000 gotenberg/gotenberg:8

# Convert HTML to PDF
curl \
  --request POST http://localhost:3000/forms/chromium/convert/html \
  --form files=@index.html \
  --form paperSize=A4 \
  --form marginTop=20mm \
  --form marginBottom=20mm \
  -o output.pdf

# Convert a URL
curl \
  --request POST http://localhost:3000/forms/chromium/convert/url \
  --form url=https://example.com \
  -o output.pdf
import requests

def generate_pdf_gotenberg(html: str) -> bytes:
    response = requests.post(
        'http://localhost:3000/forms/chromium/convert/html',
        files={'files': ('index.html', html, 'text/html')},
        data={'paperSize': 'A4', 'marginTop': '20mm', 'marginBottom': '20mm'},
    )
    response.raise_for_status()
    return response.content

Pros:

  • Language-agnostic REST API
  • Uses the rendering capabilities of Gotenberg's Chromium
  • Also converts Word, Excel, and PowerPoint files (via LibreOffice)
  • One-command Docker setup for local development

Cons:

  • Requires a container runtime — check whether your serverless platform supports it
  • Self-managed scaling (you run and scale the container)
  • Distribute and update a container containing Chromium and LibreOffice
  • Include the CJK fonts required by your documents
  • Configure the provided failure fields and implement retries in the client as needed

Best for: Teams that want a self-hosted REST API with language-agnostic access, and who also need Office document conversion. Kubernetes deployments where you manage scaling. Check container support when using serverless platforms.

7. Managed PDF API

A managed PDF API (such as FUNBREW PDF) is a hosted service. With FUNBREW, you POST HTML and then download the PDF from data.download_url in the JSON response. No server infrastructure to manage.

// Node.js
async function generatePdf(html) {
  const headers = {
    'Authorization': `Bearer ${process.env.FUNBREW_PDF_API_KEY}`,
    'Content-Type': 'application/json',
  };
  const response = await fetch('https://pdf.funbrew.cloud/api/pdf/generate-from-html', {
    method: 'POST',
    headers,
    body: JSON.stringify({
      html,
      options: {
        'page-size': 'A4',
        'margin-top': 20,
        'margin-bottom': 20,
        'margin-left': 15,
        'margin-right': 15,
      },
    }),
  });
  if (!response.ok) throw new Error(`Generation error: ${response.status}`);
  const result = await response.json();
  const pdfResponse = await fetch(result.data.download_url, { headers });
  if (!pdfResponse.ok) throw new Error(`Download error: ${pdfResponse.status}`);
  return Buffer.from(await pdfResponse.arrayBuffer());
}
# Python
import os, requests

def generate_pdf(html: str) -> bytes:
    headers = {'Authorization': f"Bearer {os.environ['FUNBREW_PDF_API_KEY']}"}
    resp = requests.post(
        'https://pdf.funbrew.cloud/api/pdf/generate-from-html',
        headers=headers,
        json={
            'html': html,
            'options': {
                'page-size': 'A4',
                'margin-top': 20,
                'margin-bottom': 20,
                'margin-left': 15,
                'margin-right': 15,
            },
        },
        timeout=30,
    )
    resp.raise_for_status()
    download_url = resp.json()['data']['download_url']
    pdf_resp = requests.get(download_url, headers=headers, timeout=30)
    pdf_resp.raise_for_status()
    return pdf_resp.content
<?php
// PHP
function generatePdf(string $html): string {
    $apiKey = getenv('FUNBREW_PDF_API_KEY');
    $headers = ['Authorization: Bearer ' . $apiKey, 'Content-Type: application/json'];
    $ch = curl_init('https://pdf.funbrew.cloud/api/pdf/generate-from-html');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => json_encode([
            'html' => $html,
            'options' => ['page-size' => 'A4'],
        ]),
    ]);
    $body = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($status !== 200) throw new RuntimeException("Generation error: HTTP $status");

    $result = json_decode($body, true, flags: JSON_THROW_ON_ERROR);
    $ch = curl_init($result['data']['download_url']);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTPHEADER => $headers,
    ]);
    $pdf = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($status !== 200) throw new RuntimeException("Download error: HTTP $status");
    return $pdf;
}

Pros:

  • Zero infrastructure management — start with an API key
  • quality uses Chromium with a paid plan and Gotenberg configuration
  • No Chromium to manage on your servers
  • Includes a Noto CJK JP font check
  • Webhooks, templates, and email delivery are available on every plan, including Free

Cons:

  • Per-request cost at scale
  • External service dependency
  • HTML is sent to a third-party server (review your data policy)

Best for: Most production applications where PDF generation is a real feature, serverless environments, and teams that do not want to maintain Chromium infrastructure. Try the Playground to verify rendering quality before committing.

Choosing the Right Method

Decision Guide

Is automation required?
  No → Browser print dialog

Is JavaScript execution before export required?
  Yes → Puppeteer, Playwright, or Managed API

What is your primary language?
  Python (no JS needed) → WeasyPrint or Managed API
  Python (JS needed)   → Playwright (Python) or Managed API
  Node.js              → Puppeteer, Playwright, or Managed API
  PHP / Ruby / Go      → Managed API or Gotenberg

Do you need to convert Office files too?
  Yes → Gotenberg

Are you on serverless (Lambda, Vercel, CF Workers)?
  Yes → Check each runtime's constraints, then choose API calls or a compatible self-hosted method

Does FUNBREW's Free quota of 30 PDFs/month cover your volume?
  Yes → Try Free. Otherwise compare paid plans with self-hosting

Do you have a strict policy against sending HTML externally?
  Yes → Self-hosted Puppeteer, Playwright, or Gotenberg

Do you want zero infrastructure maintenance?
  Yes → Managed API

Summary Table

Method Setup Resources Serverless CJK Cost
Browser print None User's browser N/A OS fonts No added service fee
wkhtmltopdf CLI Measure Check runtime constraints Font setup Self-hosted
Puppeteer Browser management Measure Check runtime constraints Font setup Self-hosted
Playwright Browser management Measure Check runtime constraints Font setup Self-hosted
WeasyPrint Python and native dependencies Measure Python runtime required Font setup Self-hosted
Gotenberg Container Measure Container runtime required Font setup Self-hosted
Managed API API key Managed by service Any environment that can call the API Verify with service Check plan and usage

Conclusion

A managed PDF API is a strong option when you want to avoid operating browsers or containers. Self-hosting can be a better fit for external-transfer restrictions, specific CSS or JavaScript behavior, runtime constraints, or existing infrastructure. Compare quality, latency, and resource use with your actual templates rather than fixed performance figures.

With FUNBREW, test templates in the Playground and check the plan's monthly quota and engine requirements. For a migration, compare API charges with measured operating and migration costs.

Related

Powered by FUNBREW PDF