October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
HTML to PNG

How to Convert HTML to PNG with WeasyPrint (CLI, Python, DPI, and Page Size)

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

Yes. WeasyPrint renders HTML and CSS directly to PNG. For a one-off conversion, run weasyprint input.html output.png. In Python, call HTML(...).write_png(); the method can save a file or return PNG bytes, width, and height. The default output density is 96 pixels per CSS inch, and CSS @page controls page dimensions, orientation, and margins.

Choose the conversion method

Use the command-line interface when a shell script or build job only needs an input and output path. Use Python when you need in-memory bytes, custom resource fetching, dynamic HTML, or per-page processing. Both paths use the same HTML/CSS layout engine.

Need Best fit Why
Single local file CLI One command and a predictable output file
HTML generated by an application Python Pass a string and keep the image in memory
Authenticated or custom assets Python with a URL fetcher The default fetcher has limited cookie and authentication support
Separate image for each page Python/document API Page objects provide page-level control

Convert HTML to PNG from the command line

Basic command

Install WeasyPrint according to the requirements for your operating system, then run:

weasyprint input.html output.png

The first argument can be a local HTML file or a supported URL; the second is the PNG file to create. To make the format explicit, use:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
weasyprint --format png input.html output.png

The CLI documents PNG and PDF output formats and includes a PNG resolution option. Check the installed version’s help for the exact option spelling:

weasyprint --help

Set PNG resolution

WeasyPrint’s documented default is 96 PNG pixels per CSS inch. At 96 dpi, a CSS pixel maps to one PNG pixel. Increase the resolution for a denser image or lower it to reduce dimensions and file size. The CLI exposes the corresponding PNG-resolution setting; use the option shown by weasyprint --help with your version.

Make the page dimensions deterministic

Put dimensions in the stylesheet rather than relying on a command-line paper-size switch:

@page {
  size: 1200px 800px;
  margin: 0;
}

html, body {
  margin: 0;
}

@page also accepts named paper sizes, orientation, and physical units. Removing margins from both @page and the document’s root elements avoids an unexpected border around the capture.

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

Convert HTML to PNG with Python

Render a string

from weasyprint import HTML

html = HTML(string="<h1>Hello</h1><p>Rendered as PNG.</p>")
html.write_png("output.png")

write_png() accepts a filename (or file-like target, depending on your environment). If you omit the target, it returns PNG bytes together with the rendered width and height:

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
from weasyprint import HTML

png_bytes, width, height = HTML(
    string="<h1>Report</h1>"
).write_png()

with open("report.png", "wb") as f:
    f.write(png_bytes)
print(width, height)

Keeping bytes in memory is useful when an HTTP response, object-storage upload, or image pipeline should receive the result without a temporary file.

Render a local file or URL

from weasyprint import HTML

HTML(filename="input.html").write_png("output.png")
HTML(url="https://example.com/page").write_png("page.png")

Relative images, stylesheets, and fonts resolve relative to the document’s base URL when WeasyPrint knows it (for example, with filename or url). For a string, supply a base_url if it references relative assets:

from weasyprint import HTML

HTML(
    string='<img src="images/logo.png" alt="Logo">',
    base_url="/srv/site"
).write_png("logo-page.png")

Change resolution in Python

from weasyprint import HTML

HTML(filename="input.html").write_png(
    "output-144dpi.png",
    resolution=144,
)

The documented default is 96 dpi. Resolution changes the PNG pixel density; it does not replace CSS layout rules. Set the CSS page size first, then choose a resolution that matches the downstream display or print workflow.

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

Control size, orientation, and margins with CSS

Fixed pixel canvas

@page {
  size: 1200px 800px;
  margin: 0;
}

body {
  margin: 0;
  background: white;
}

Landscape paper

@page {
  size: A4 landscape;
  margin: 12mm;
}

For a document intended to be a screenshot-like canvas, pixel dimensions and zero margins are usually clearer. For a report, a named paper size with physical margins is easier to maintain.

Prevent awkward page breaks

.card {
  break-inside: avoid;
}

h2 {
  break-after: avoid;
}

These rules affect where content is split before it is painted into the PNG. Test long tables, images, and headings at the final page size.

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

What happens with multiple pages?

When the HTML lays out as multiple pages, WeasyPrint paints them vertically into one PNG. The resulting image uses the width of the widest page, and each page is centered horizontally. This is convenient for a single tall preview but can create a very large bitmap for long documents.

When you need one PNG per page

Use the rendered document’s page-level objects and paint each page onto its own Cairo surface. The documented Document API exposes this control. A typical workflow is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Build an HTML object and call its document-rendering method.
  2. Iterate over the document’s pages.
  3. Create a surface with the page’s pixel dimensions.
  4. Paint that page, finish the surface, and save its PNG.

The exact Cairo integration depends on the versions of WeasyPrint and Cairo installed together, so verify the page-surface API in your installed documentation before deploying it.

Assets, URLs, fonts, and CSS support

Supported resource locations

WeasyPrint accepts local files, HTTP, FTP, and data URLs. Embedded PNG and JPEG images are supported. Give local documents a correct base_url or use filename so relative resources can be found.

Authenticated resources

The default HTTP fetcher does not provide advanced cookie or authentication handling. If your HTML loads protected images, stylesheets, or fonts, provide a custom URL fetcher that adds the required headers, cookies, or credentials. Do not put long-lived secrets directly into public HTML.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

SVG and unsupported CSS

WeasyPrint treats SVG as vector content in PDF output; verify the PNG result when the design depends heavily on SVG. The renderer can warn about unsupported CSS properties. Read warnings, then test the actual fonts, external assets, media rules, and @page declarations used by production documents. Browser-only features and JavaScript-driven layout should not be assumed to behave like a full browser.

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

Reliable conversion workflow

  1. Freeze the input. Save the exact HTML, CSS, fonts, and images used for a render.
  2. Define the canvas. Add an explicit @page size, orientation, and margin.
  3. Set the base URL. Use filename, url, or base_url so relative links resolve.
  4. Choose resolution. Start at the 96-dpi default, then change it only when pixel density requires it.
  5. Capture warnings. Treat missing assets and unsupported CSS warnings as conversion failures for pixel-sensitive output.
  6. Inspect dimensions. Check the PNG width and height, especially for multi-page documents that become very tall.
  7. Compare representative pages. Include long text, tables, SVG, web fonts, and images in visual regression tests.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting common failures

The command is not found

WeasyPrint is not installed in the active environment or its executable is outside PATH. Activate the intended virtual environment, install WeasyPrint using its platform instructions, and run weasyprint --version.

The PNG is blank or missing content

Check that the input URL or filename is reachable, the HTML has a usable base_url, and external resources return successfully. Inspect stderr for fetch and CSS warnings. JavaScript that creates content after load may not run as it would in a browser; generate that content in the HTML before passing it to WeasyPrint.

Images or fonts are missing

Replace relative paths with a correct base URL, confirm file permissions, and verify that HTTP resources do not require cookies or authorization. Use a custom fetcher for protected assets.

The output size is wrong

Look for default body margins, an unexpected @page rule, physical units, or a resolution setting different from 96 dpi. Define the page size and margins explicitly, then inspect the returned width and height.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

CSS does not match a browser

Read WeasyPrint’s unsupported-property warnings and simplify browser-specific CSS. Test the exact stylesheet and fonts; a browser screenshot and a document renderer do not guarantee identical layout.

A very long document exhausts memory

A vertically stacked multi-page PNG must hold a large bitmap. Reduce the page dimensions or resolution, split the document into page images, or use PDF when a single raster image is not required.

Or skip the browser setup

If your goal is a clean website capture rather than document-style HTML rendering, ScreenshotNeo provides a single HTTP request and supports PNG, JPEG, WebP, and PDF. It accepts cookie and consent banners before capture and removes 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.

Use the API documented at https://screenshotneo.com/docs/:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo also offers an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

CLI versus Python: practical trade-offs

Consideration CLI Python
Integration Shell scripts and build systems Application code and services
Output Named PNG file File or in-memory bytes plus dimensions
Dynamic HTML Write a file first Pass a string directly
Resource control Basic command options Custom fetchers and application logic
Multiple pages Single vertically stacked PNG Page-level processing is possible

Frequently asked questions

Can WeasyPrint convert a remote web page?

Yes. Use HTML(url="https://example.com/page") or the CLI with a URL, provided the page and its resources are accessible to the fetcher.

Does PNG resolution change CSS dimensions?

No. CSS determines layout; the resolution setting changes the density and resulting pixel dimensions of the raster output.

Can I get PNG bytes without writing a file?

Yes. Call write_png() without a target and handle the returned bytes and dimensions in Python.

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

Is one PNG per page the default?

No. Multi-page HTML is combined into one vertically stacked PNG. Separate files require page-level document processing.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

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

Read next

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.