Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use WeasyPrint when you need a Python API for print-oriented HTML/CSS, or Playwright when you need a real browser’s rendering behavior. Neither choice guarantees pixel-identical output for every template. Render representative documents on the same operating system and dependency versions used in production, then inspect pagination, fonts, images, links, tables, and any right-to-left text.

This guide shows both implementations, the CSS that controls page geometry, deployment and security checks, troubleshooting, and a hosted alternative when you do not want to maintain a browser runtime.

Choose the conversion route first

The right renderer depends on the HTML and CSS you actually use, not on a generic claim that one library is “best.” WeasyPrint exposes a direct Python API and is designed around print-oriented layout. Playwright opens the page in an automated browser and calls its PDF method, which uses print media by default. ReportLab is a separate PDF-generation toolkit rather than evidence of direct HTML conversion, while old Django wrappers around wkhtmltopdf should be treated as legacy integration material until current upstream status is verified.

Option Useful when Investigate before production
WeasyPrint Python-facing HTML/CSS-to-PDF conversion with CSS page rules and print layout. Python/Pango and other native dependencies, supported CSS features, external resource loading, and isolation of untrusted input.
Playwright for Python You need browser rendering, JavaScript-driven pages, or close alignment with Chromium’s layout. Browser installation and updates, readiness of the page before printing, print versus screen CSS, and runtime footprint.
ReportLab You are designing a PDF directly with a PDF-generation toolkit. It is not a drop-in HTML converter; expect a different document-building model.
wkhtmltopdf integration You are maintaining an existing Django integration. The available wrapper material is old third-party documentation. Verify the current upstream project, security posture, and platform support.

Compare the HTML/CSS features your templates use, fidelity on real documents, dependencies in deployment, remote-resource policy, PDF requirements such as page size or accessibility variants, and expected throughput. Published documentation does not establish a neutral speed benchmark, so measure your own workload.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Convert HTML with WeasyPrint

Install and verify native dependencies

Install the Python package in the environment that will perform conversion:

python -m pip install weasyprint

Current WeasyPrint first-steps documentation lists Python and Pango among its requirements. Operating-system packages and names vary by release, Linux distribution, macOS setup, and Windows environment; check the release-specific installation instructions before building your image or deployment package. A successful pip install alone does not prove that native libraries are available.

Render a string to a PDF

This is the smallest complete example and follows the API shown in the project documentation:

from weasyprint import HTML

html = '''



  
  Invoice
  


  

Invoice 1007

Rendered from an in-memory HTML string.

''' HTML(string=html).write_pdf('invoice.pdf')

HTML accepts a filename, URL, readable file object, or in-memory string. When the document references relative images, stylesheets, or fonts, provide a meaningful base URL (for example, the directory containing the HTML) so those resources can be resolved.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Render an HTML file with a base URL

from pathlib import Path
from weasyprint import HTML

source = Path('templates/report.html').resolve()
output = Path('build/report.pdf')
output.parent.mkdir(parents=True, exist_ok=True)

HTML(filename=str(source), base_url=source.parent.as_uri()).write_pdf(str(output))
print(f'Wrote {output}')

Control paper size, margins, and page breaks in CSS

For WeasyPrint, page geometry belongs in print CSS. The documented starting pattern is:

@page {
  size: A4;
  margin: 2cm;
}

@page :first {
  margin-top: 3cm;
}

h2, h3 { break-after: avoid; }
table, figure { break-inside: avoid; }
.page-break { break-before: page; }

Use the paper size and margin units required by your document, then inspect overflow and pagination rather than assuming that a rule that looks correct in a browser will produce the same pages. WeasyPrint documents many print features, but its coverage is not universal; right-to-left or bidirectional text is one explicitly documented limitation area. Test Arabic, Hebrew, mixed-direction content, complex tables, and special fonts if they matter to your users.

External assets and fonts

Images, CSS, and fonts must be readable by the converter. Prefer deterministic, versioned assets and a controlled base URL. A missing font can change line wrapping and therefore every subsequent page break. Check the generated PDF on the deployment host, not only on a developer laptop.

Convert HTML with Playwright for Python

Install the package and browser

python -m pip install playwright
python -m playwright install chromium

The second command installs a browser runtime. In containers or locked-down servers, account for its size, sandbox policy, executable dependencies, and update process.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Print a URL with the synchronous API

from pathlib import Path
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto('https://example.com/report', wait_until='networkidle')
    page.pdf(
        path='report.pdf',
        format='A4',
        margin={'top': '20mm', 'right': '20mm', 'bottom': '20mm', 'left': '20mm'},
        print_background=True,
    )
    browser.close()

Playwright’s PDF API generates with print media by default. If the page is intentionally styled for the screen and you need those rules, call page.emulate_media(media='screen') before page.pdf(). Otherwise keep print CSS as the source of truth.

Print local HTML and wait for application readiness

from pathlib import Path
from playwright.sync_api import sync_playwright

html_path = Path('templates/report.html').resolve()
url = html_path.as_uri()

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto(url, wait_until='networkidle')
    page.wait_for_selector('#report-ready')
    page.pdf(path='report.pdf', format='A4', print_background=True)
    browser.close()

Use an explicit readiness marker when your application fills data asynchronously. A network-idle condition alone may be misleading on pages with analytics, long polling, or delayed rendering. Confirm that images, charts, and web fonts are loaded before printing.

Make templates predictable

  • Keep print rules in a dedicated stylesheet or a clearly marked @media print section.
  • Define @page size and margins instead of relying on viewer defaults.
  • Use stable table layouts and test rows that span page boundaries.
  • Choose fonts available on every conversion host and package the font files when licensing permits.
  • Give images intrinsic dimensions and verify that remote URLs are reachable from the worker.
  • Test links, headers, footers, page numbers, backgrounds, and forms if your PDF requirement includes them.
  • If archival or accessibility output is required, verify the renderer’s documented PDF/A or PDF/UA capabilities and validate the resulting file; do not infer compliance from a successful conversion.

Security: treat HTML and CSS as input

WeasyPrint explicitly warns that untrusted HTML or CSS can create security problems and documents resource-loading concerns. User-controlled markup, styles, and URLs can cause unexpected network requests or access to resources available to the conversion process. Before accepting such content:

  • Run conversion in a restricted worker or container with minimal filesystem and network permissions.
  • Allow-list remote origins and resource types, or serve sanitized, local assets.
  • Set job timeouts and process limits; terminate stuck workers.
  • Do not pass secrets in page URLs, HTML, headers, or environment variables visible to untrusted templates.
  • Keep WeasyPrint, Playwright, the browser, and native libraries patched according to your deployment policy.

Review the current security guidance for the renderer and test the exact resource-fetching behavior in your version. Isolation is an application responsibility, not something to assume from a conversion API.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Reliability and performance in production

Measure the real document

Build a fixture set containing your longest report, the largest images, dense tables, missing-data cases, non-Latin text, and pages with intentional breaks. Compare PDFs produced on the target operating system and dependency versions. Record conversion time, output size, memory use, page count, and failure reason.

Choose a worker model

WeasyPrint avoids a full browser process but still depends on native libraries and document complexity. Playwright requires a browser process and benefits from controlled reuse, while each job must be isolated from data belonging to another job. Start with a small worker pool, enforce per-job timeouts, and monitor browser crashes, native-library errors, and asset-fetch failures.

Cache safely

Cache only when the HTML, CSS, assets, locale, and data version are part of the cache key. Invalidate when fonts or templates change. Never reuse a PDF containing user data for another user because the URL or template name happens to match.

Troubleshooting common failures

Symptom Likely cause Fix
Import error mentioning Pango or a shared library Required native dependency is absent or not discoverable. Install the packages listed for your WeasyPrint release and operating system; rebuild the deployment image and run a conversion smoke test.
Images or CSS are missing Relative URLs have no usable base URL, or the worker cannot reach the resource. Pass base_url, use absolute allow-listed URLs, and verify permissions and network access from the worker.
Browser PDF is blank or incomplete The page was printed before client-side rendering finished. Wait for a deterministic selector or application-ready signal; inspect console and network errors.
Layout differs from the browser preview Print media rules, fonts, viewport, or page margins differ. Decide whether print or screen media is authoritative, set the required media explicitly, and test with production fonts and dimensions.
Unexpected page breaks Content height changed because of fonts, images, or unsupported CSS. Set intrinsic image sizes, review @page margins, use break rules, and test the exact renderer version.
Right-to-left text is incorrect Renderer feature coverage does not meet the template’s bidirectional-text needs. Render representative Arabic or Hebrew documents early and evaluate a browser route or another engine if the result is unacceptable.
Jobs hang on external URLs A resource is slow, unavailable, or never finishes loading. Restrict outbound access, add timeouts, avoid indefinitely running requests, and log the URL and failure class without exposing secrets.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

ScreenshotNeo is a hosted website screenshot API and MCP server. Give it a page URL with one GET request instead of packaging a browser. It can return a PDF as well as PNG, JPEG, or WebP; for the PDF response and all available options, see the ScreenshotNeo API documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

The following examples use the supplied request shape; replace the target URL with the page you want to capture.

cURL

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp

Python

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://example.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Before capture, ScreenshotNeo can accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.

Every plan includes the features. The Free plan provides 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots, followed by Growth at $15 for 15,000, Pro at $39 for 60,000, Scale at $99 for 250,000, and Business at $249 for 1,000,000. Yearly billing gives two months free.

For a hosted capture workflow, sign up for ScreenshotNeo and start with the free 1,000-shot allowance without adding a card.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Practical decision checklist

  1. List the CSS, fonts, JavaScript behavior, remote assets, and PDF variants your template requires.
  2. Render representative documents with WeasyPrint and Playwright when both are viable.
  3. Inspect page geometry, pagination, links, images, tables, and bidirectional text on the deployment platform.
  4. Choose the renderer whose documented capabilities and operational dependencies fit the project, then pin and monitor its versions.
  5. For untrusted or externally hosted pages, apply resource restrictions, timeouts, and isolation before exposing conversion as an endpoint.

Frequently Asked Questions

Can a Python converter produce a PDF from an HTML string without creating a temporary file?

Yes. WeasyPrint accepts an in-memory string through `HTML(string=…)` and writes the resulting bytes to a PDF path.

Why does the same page have different pagination on two servers?

Fonts, native library versions, browser versions, page margins, and loaded assets can all change line wrapping and page breaks. Compare the complete runtime environments, not only your Python package versions.

Should I use screen or print styles for Playwright PDFs?

Playwright uses print media by default. Keep that behavior unless the design specifically requires screen media, in which case call `page.emulate_media(media=’screen’)` before printing and test the result.

The Bottom Line

Start with WeasyPrint for a Python-native, print-focused pipeline; use Playwright when browser rendering or client-side readiness is central. Validate real templates on the production runtime, secure resource loading, and choose a hosted API when maintaining the conversion environment is not worth the operational work.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.