HTML to image in Python with Playwright: 312 KB as PNG, 12.5 KB as WEBP
A headless browser turns an HTML snippet into a social card, a banner or a receipt. On 4 November 2026 the same 1200 x 630 card came out at 312 KB as PNG, 26.2 KB as JPEG and 12.5 KB as WEBP, and one browser drew 50 cards in 2.6 s where a browser per card took 38.9 s. The code, and the traps: a white margin, late fonts, a made-up bold, emoji as boxes and lost transparency.
Social cards, banners, certificates and receipts are easy to lay out in HTML and CSS. A headless browser then draws them as an image. In Python that browser is usually Chromium, driven by Playwright: you pass the HTML as a string and take a screenshot of the window.
On 4 November 2026 we did that on our server with Playwright 1.58.0, Chromium 145 and Pillow 10.4.0. We drew cards of 1200 x 630 pixels, the common size for link previews, a badge on a transparent background and a receipt, and measured the files, the time and what ended up in the pixels. Screenshots of live websites have traps of their own, covered in Website screenshot in Python. Here the HTML is yours.
The short version#
- WEBP is the smallest, PNG can be huge. A card with a gradient was 312.0 KB as PNG, 26.2 KB as JPEG at quality 80 and 12.5 KB as WEBP at quality 80. The same card on one flat colour was 20.4 KB as PNG, smaller than the JPEG at quality 80 (25.0 KB). Lossless WEBP was the smallest of all there, 6.6 KB.
- scale=2 doubles each side. With
device_scale_factor=2the 1200 x 630 card came out 2400 x 1260, with the same layout, for sharp images on high-density screens. The gradient PNG grew to 969.2 KB, the WEBP to 26.5 KB. - Start one browser for many images. 50 gradient cards through one browser took 2.6 s as JPEG (52 ms a card) and 13.3 s as PNG (267 ms a card). One call per card, each starting Playwright and Chromium again, took 38.9 s and 45.0 s: a median of 763 and 879 ms a card.
- PNG is the slow format. Of the time per card, the PNG took 186 ms (median of 50) and the JPEG 36 ms. On the flat card the PNG took 43 ms. Loading the HTML with
set_contenttook 4 ms. - Web fonts made it into every picture. A font from Google Fonts was still loading at the load event, 5 times out of 5. Playwright's screenshot waits for fonts itself, and all 5 images had it.
- Emoji and non-Latin text need fonts on the server. With only the DejaVu fonts, 5 of 6 emoji and every Japanese, Chinese, Korean, Thai and Hindi character we tried came out as boxes.
The code#
html_to_images() takes a list of (HTML, file name) pairs and draws them all with one browser and one page. The file name picks the format. Playwright writes PNG and JPEG only, so WEBP goes through Pillow, which keeps the transparency. full_page=True makes the image as tall as the content, for receipts and anything else of unknown height. Without a quality, Playwright's JPEG was byte for byte the same as at quality 80, so that default changes nothing.
import io
from playwright.sync_api import sync_playwright
from PIL import Image
KINDS = {"png": "png", "jpg": "jpeg", "jpeg": "jpeg", "webp": "webp"}
def html_to_images(jobs, width=1200, height=630, scale=1, transparent=False, quality=80, full_page=False):
"""Render [(html, path), ...] with one browser. The file name picks the format: .png, .jpg or .webp.
width and height are CSS pixels; scale=2 makes the image twice as wide and twice as tall."""
kinds = [KINDS[path.rsplit(".", 1)[-1].lower()] for _, path in jobs]
if transparent and "jpeg" in kinds:
raise ValueError("JPEG has no transparency: use .png or .webp")
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page(viewport={"width": width, "height": height}, device_scale_factor=scale)
for (html, path), kind in zip(jobs, kinds):
page.set_content(html, wait_until="load") # not "domcontentloaded": the font CSS may not be in yet
if kind == "jpeg":
page.screenshot(path=path, type="jpeg", quality=quality, full_page=full_page)
continue
png = page.screenshot(omit_background=transparent, full_page=full_page) # waits for web fonts
if kind == "png":
with open(path, "wb") as f:
f.write(png)
else: # Playwright writes PNG and JPEG only
Image.open(io.BytesIO(png)).save(path, "WEBP", quality=quality)
browser.close()import os
CARD = ('<!doctype html>'
'<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap">'
'<style>body { margin: 0 } .card { width: 1200px; height: 630px; box-sizing: border-box; padding: 80px;'
' color: #fff; font-family: Inter, sans-serif; background: linear-gradient(135deg, #0f2027, #2c5364) }'
' h1 { font-size: 72px; margin: 0 0 24px } p { font-size: 32px; margin: 0 }</style>'
'<div class="card"><h1>%s</h1><p>%s</p></div>')
BADGE = ('<style>body { margin: 0 }</style><div style="width: 300px; height: 100px; margin: 50px;'
' border-radius: 24px; background: #e4572e"></div>')
RECEIPT = ('<style>body { margin: 0; padding: 24px; font: 16px/1.5 monospace }</style><b>Order 1042</b>'
+ "".join(f'<div>Item {i}<span style="float: right">{i * 3}.00</span></div>' for i in range(1, 13)))
html_to_images([(CARD % ("HTML to image in Python", "Cards, banners, receipts"), "card." + ext)
for ext in ("png", "jpg", "webp")])
html_to_images([(CARD % ("Twice as sharp", "scale=2"), "card@2x.webp")], scale=2)
html_to_images([(BADGE, "badge.png"), (BADGE, "badge.webp")], width=400, height=200, transparent=True)
html_to_images([(RECEIPT, "receipt.png")], width=380, height=100, full_page=True)
for name in ("card.png", "card.jpg", "card.webp", "card@2x.webp", "badge.png", "badge.webp", "receipt.png"):
im = Image.open(name)
print(name, im.size, im.mode, round(os.path.getsize(name) / 1024), "KB")It printed 1200 x 630 for the three cards: 309 KB as PNG, 24 KB as JPEG and 11 KB as WEBP. With scale=2 the WEBP was 2400 x 1260 and 18 KB. The badge came out RGBA, with an alpha channel, as PNG (2 KB) and as WEBP (1 KB). The receipt had a window of 380 x 100 and came out 380 x 360: with full_page=True the image follows the content.
In the timing run, one of the 50 calls that each started a fresh browser failed once with Unable to capture screenshot and worked when tried again. In a long batch, catch errors per item and retry.
The traps#
- The page has a margin of its own. Unless your CSS says otherwise, Chromium gives the body a margin of 8px. A 1200 x 630 card in a 1200 x 630 window came out with a white strip along the top and the left side, 14,576 white pixels. The page was 1208 x 646, so the right and bottom edges of the card were cut off. Put
body { margin: 0 }in the HTML, or take the picture of the element:page.locator("div").screenshot()came out 1200 x 630, with the card's colour right in the corner. - Wait for load, not for domcontentloaded. A Google Fonts stylesheet asks for the font file late. At the load event
document.fonts.statusstill said "loading", 5 times out of 5. The picture was right anyway, because Playwright's screenshot waits fordocument.fonts.readybefore it takes the picture. Withwait_until="domcontentloaded"the stylesheet was not in yet, and all 5 images had the fallback font, DejaVu Sans: 33,300 pixels different. Waiting fordocument.fonts.readyafter that did not help. It resolved at once, with 0 fonts known, and the 5 images still had the fallback font. - A screenshot over the DevTools protocol does not wait for fonts. Chromium can take the picture itself, through a CDP session and
Page.captureScreenshot. Right after load, 5 of 5 such pictures had the fallback font. That route is tempting for WEBP: Chromium wrote it in 69 ms, against 186 ms for the PNG plus 52 ms in Pillow. If you take it, wait fordocument.fonts.readyyourself first. - Ask Google Fonts for the weight you use.
family=Intersends weight 400 only. A bold heading then gets a bold that the browser makes up: 518 px wide, against 530 px with the real weight fromfamily=Inter:wght@700, and 10,275 pixels different. List every weight in the link, such aswght@400;700. - A server without fonts draws boxes. Our server has 479 font faces (lines of
fc-list), and everything we tried came out right, the emoji in colour. Limited to DejaVu, 22 font faces, 5 of 6 emoji came out as boxes and none in colour, and so did every Japanese, Chinese, Korean, Thai and Hindi character. Hebrew, Arabic, Cyrillic and Greek were fine.playwright install-deps chromiumlists the font packages it installs: fonts-noto-color-emoji, fonts-ipafont-gothic, fonts-wqy-zenhei, fonts-tlwg-loma-otf, fonts-liberation, fonts-freefont-ttf, fonts-unifont, xfonts-cyrillic and xfonts-scalable. With DejaVu plus just those packages, every test character came out right again, the emoji in colour. - A background in the CSS cancels transparency.
omit_background=Truegives a PNG with an alpha channel only when neither html nor body has a background. A badge with rounded corners came out with see-through corners, (0, 0, 0, 0), and 184 partly see-through pixels along the curves. Withbody { background: #fff }, or the same on html, the PNG came back with no alpha channel at all (RGB), white in the corner. - JPEG has no transparency, and it does not tell you.
omit_background=Truewithtype="jpeg"gave no error: the corners came out white, (255, 255, 255). Pillow refuses outright: saving the RGBA image as JPEG raisedOSError: cannot write mode RGBA as JPEG.html_to_images()turns down a transparent JPEG before it starts. What.convert("RGB")does to see-through pixels is in Convert images in Python with Pillow.
Many images at once#
For many images at once, our HTML to Image Converter on Apify does the rendering. Give it HTML snippets or whole documents, up to 1,000 in a run, with a size or the full height of the page, a pixel ratio for retina images, and a transparent background where the format has one. Each item comes back with a link to its PNG, JPEG or WEBP file, the MIME type, the size in bytes and the time it took, or with an error of its own. Scripts in the HTML are not run, so a card has to be complete without JavaScript, as all of ours above are. It does not remove the default 8 px body margin, so put body { margin: 0 } in your HTML. Its defaults are png, a width of 1200 and a quality of 90; set quality to 80 to compare with the sizes above. It is billed per successfully processed item, which is one image; a failed item is not charged. How to set it up, step by step: HTML to image export.
written
16 min readDownload all files from a website in Python: 964 file links and the traps we measured
We listed every file link on 12 public pages, 964 of them, and asked for 458 of them politely. The servers were tidy: 456 of 458 HEAD answers were 200 with the usual type. The traps sat elsewhere: a page that redirects, a robots.txt that answers 403, wildcard rules that urllib.robotparser misreads, a HEAD that says 0 bytes, and PDFs of almost 70 MB.
7 min readCheck domain availability in Python with RDAP: 150 of 150 four-letter .com names were taken
RDAP is the open successor of WHOIS: ask the registry of the TLD, and a 404 means no one has registered the name. We checked 530 names on 3 November 2026. All 150 random four-letter .com names were taken, and 13 of 50 random five-letter ones. The Python code, and the 404s that do not mean available.
4 min readConvert images in Python with Pillow: WebP sizes, and the two bugs that ship
On the 24 Kodak test photos, WebP at the quality of JPEG 80 was two thirds of the JPEG size, and lossless WebP about three quarters of an optimized PNG. A converter in 30 lines of Pillow, and the two bugs a quick one ships: transparent parts that turn black, and phone photos that turn sideways.