Use WeasyPrint to render HTML/CSS to PDF, pass that PDF to pdf2image when you need PNG or JPEG pages, and use python-docx to build a structured Word document. These are different jobs: python-docx is a DOCX authoring library, not a general-purpose HTML-to-DOCX renderer. For arbitrary web pages, test fonts, images, CSS, authentication, and page breaks with representative input before choosing a production workflow.
Choose the conversion path first
| Required output | Practical Python route | What it preserves | Main qualification |
|---|---|---|---|
| WeasyPrint HTML/CSS renderer | Printed layout, styles, fonts, images, page breaks | Installation may require operating-system libraries; external authentication is not enabled by the default fetcher. | |
| PNG or JPEG pages | HTML → PDF with WeasyPrint → images with pdf2image | The PDF renderer determines layout; the rasterizer determines resolution and image format | pdf2image consumes PDF input rather than rendering HTML directly. |
| Editable DOCX | python-docx, constructing paragraphs, headings, tables, and pictures | Structured Word content you explicitly create | Its documentation does not establish faithful, general HTML-to-DOCX conversion. |
| Hosted rendering | A service such as HTML2Image’s documented Python client | Provider-defined image or PDF rendering | Verify current Python requirements, credits, pricing, privacy, and limits on the vendor site. |
There is no neutral benchmark in the available documentation that proves one approach is universally fastest or most faithful. Evaluate your own HTML, CSS, assets, and security constraints.
Prepare a reproducible Python project
Install the libraries
python -m venv .venv
# macOS/Linux
source .venv/bin/activate
# Windows PowerShell
# .venvScriptsActivate.ps1
python -m pip install weasyprint pdf2image python-docx
WeasyPrint can need additional native libraries depending on your operating system. Follow its current installation guidance for the target machine, container, or CI image instead of assuming that a successful local install will deploy unchanged.
Use a self-contained test document
from pathlib import Path
html = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
@page { size: A4; margin: 18mm; }
body { font-family: sans-serif; color: #222; }
h1 { color: #174ea6; }
.avoid-break { break-inside: avoid; }
</style>
</head>
<body>
<h1>Quarterly report</h1>
<p class="avoid-break">Rendered by Python.</p>
</body>
</html>"""
Path("report.html").write_text(html, encoding="utf-8")
When your HTML references relative images, stylesheets, or fonts, keep the document and assets in a predictable directory and provide a base URL to the renderer.
Free tools Windows power users keep installed
One-click scans. No signup required.
#1 Best Overall
- 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 and CSS to PDF with WeasyPrint
Render a file
from weasyprint import HTML
HTML(filename="report.html", base_url=".").write_pdf("report.pdf")
Render a URL or an in-memory string
from weasyprint import HTML
HTML(url="https://example.com").write_pdf("page.pdf")
html = "<h1>Invoice</h1><p>Amount due: $125</p>"
pdf_bytes = HTML(string=html, base_url="/absolute/path/to/assets").write_pdf()
with open("invoice.pdf", "wb") as f:
f.write(pdf_bytes)
The HTML object accepts a filename, URL, readable file object, or string. write_pdf() writes directly to a destination, or returns PDF bytes when no destination is supplied. Pass stylesheets explicitly when you keep CSS outside the HTML:
from weasyprint import HTML, CSS
HTML(filename="report.html", base_url=".").write_pdf(
"report.pdf",
stylesheets=[CSS(filename="print.css")]
)
Load web fonts
from weasyprint import HTML
from weasyprint.text.fonts import FontConfiguration
fonts = FontConfiguration()
HTML(filename="report.html", base_url=".").write_pdf(
"report.pdf",
font_config=fonts
)
Use the documented font configuration pattern for @font-face. Check that the font files are reachable in the runtime and licensed for your use.
Understand resource fetching and access limits
WeasyPrint’s ordinary URL fetcher can retrieve linked stylesheets and images, but its documentation says cookies and authentication are not supported by default. A protected page may therefore render without its assets or fail to load them. A custom URL fetcher can add the headers or credentials your application is allowed to use; avoid embedding secrets in public HTML and test redirects, TLS certificates, relative URLs, and timeouts.
Convert the rendered PDF into PNG or JPEG images
Install and convert every page
from pdf2image import convert_from_path
pages = convert_from_path("report.pdf", dpi=150)
for number, page in enumerate(pages, start=1):
page.save(f"report-{number:03d}.png", "PNG")
This two-stage design lets the HTML renderer handle pagination and CSS, while pdf2image rasterizes each PDF page. Confirm the PDF utility required by your platform against the current pdf2image instructions.
Rank #2
- 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.
Control format, resolution, and page range
from pdf2image import convert_from_path
pages = convert_from_path(
"report.pdf",
dpi=200,
first_page=2,
last_page=4,
fmt="jpeg",
thread_count=2
)
for number, page in enumerate(pages, start=2):
page.save(f"report-{number}.jpg", "JPEG", quality=92)
Higher DPI increases pixel dimensions, memory use, and processing time. For thumbnails, use a lower DPI; for print-oriented images, choose a resolution based on the final physical size. Keep page ranges explicit when a large PDF would otherwise create unnecessary files.
Create a Word document with python-docx
Build editable structure from selected content
from docx import Document
from docx.shared import Inches
out = Document()
out.add_heading("Quarterly report", level=1)
out.add_paragraph("This paragraph is editable in Word.")
table = out.add_table(rows=1, cols=2)
table.style = "Table Grid"
table.rows[0].cells[0].text = "Metric"
table.rows[0].cells[1].text = "Value"
row = table.add_row().cells
row[0].text = "Revenue"
row[1].text = "$125,000"
out.add_picture("chart.png", width=Inches(5.8))
out.save("report.docx")
python-docx documents operations for creating and updating DOCX files, including paragraphs, headings, tables, and pictures. It does not document a browser-like HTML/CSS layout engine. For a page whose exact visual appearance matters, keep the PDF (or images) as the fidelity target and treat the DOCX as a separately designed, editable representation.
Map HTML deliberately
- Map
h1–h6to Word heading levels. - Convert text nodes to paragraphs and lists to Word list styles.
- Translate tables cell-by-cell and download images before inserting them.
- Decide how to handle CSS-only effects, positioned elements, SVG, video, scripts, and forms; these have no automatic DOCX equivalent.
Handle assets, fonts, and protected pages
- Relative paths: supply a correct
base_url(often the HTML file’s directory or an absolute asset root). - Remote images and CSS: verify network access from the conversion host, not just from your laptop.
- Authentication: the default WeasyPrint fetcher does not provide cookies or authentication. Use a controlled custom fetcher or pre-download permitted assets.
- Fonts: package the exact font files, configure
@font-face, and check fallback glyphs for non-Latin text. - JavaScript: a static HTML renderer is not a substitute for a browser executing application code. If content appears only after scripts run, obtain the final HTML or use a browser-based capture service.
- Page breaks: use print CSS such as
@page,break-before,break-after, andbreak-inside, then inspect long tables and headings at page boundaries.
Or skip the browser setup
ScreenshotNeo is a hosted website screenshot API and MCP server. It accepts a URL and returns PNG, JPEG, WebP, or PDF. Before capture it accepts cookie/consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers identify the page verdict and whether it was billed. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo API documentation for output and options. The same endpoint supports full-page capture, CSS-element capture, dark mode, device presets and custom viewports, retina scale, PDF paper settings and page ranges, custom CSS or JavaScript, clicks, selector waits, delays or network-idle waits, request blocking, headers, cookies, user agents, Authorization, timezone, geolocation, transparent backgrounds, resizing, chosen-TTL caching, signed image links, asynchronous webhooks, bulk capture of up to 100 URLs per call, usage reporting, and an OpenAPI specification.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsimport requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));
The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free, and every feature is on every plan. Create a free ScreenshotNeo account.
Rank #3
- 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.
Hosted HTML rendering as another option
HTML2Image documents an official Python client for an HTML-to-image API and mentions an HTML-to-PDF API. Its vendor page stated Python 3.9 or newer and 50 starting free credits when crawled; those are changeable service terms, so verify them before adoption. A hosted service can remove local system-library work, but compare its current pricing, privacy terms, fidelity, quotas, and availability with your requirements.
Make conversions reliable in production
Validate before publishing files
- Check that the output exists, has a nonzero size, and can be opened by a PDF, image, or DOCX parser.
- Compare page count and expected headings; missing fonts or assets can otherwise look like a successful conversion.
- Keep a representative fixture containing long text, tables, remote assets, special characters, and page breaks.
- Set process timeouts and isolate untrusted HTML, CSS, URLs, and JavaScript according to your security policy.
Control cost and throughput
Local conversion has no per-call vendor fee, but native dependencies, CPU, memory, fonts, and asset downloads become your operational cost. Reuse downloaded assets and avoid rasterizing pages you do not need. For a hosted API, measure your actual document mix and confirm billing rules and limits; the available material does not establish a neutral cost or speed winner.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Troubleshooting common failures
Import or installation errors
Symptom: WeasyPrint imports fail or native-library errors appear. Fix: install the platform dependencies listed in the current WeasyPrint guide, recreate the virtual environment, and test the same base image used in deployment.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Blank or incomplete PDF
Cause: relative paths, blocked network requests, missing fonts, or content generated only by JavaScript. Fix: set base_url, log fetch failures, package assets, provide permitted authentication through a custom fetcher, or capture the post-render HTML.
Rank #4
- 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
Images do not appear
Cause: the image URL is inaccessible from the server or requires cookies. Fix: test the URL from the conversion host, use absolute paths, prefetch authorized files, and confirm the image format is supported.
pdf2image cannot convert
Cause: the required PDF rendering utility is missing or not on PATH. Fix: install the utility required by your operating system, verify it from the same environment, and pass its path when the library supports that configuration.
DOCX layout differs from the page
Cause: python-docx creates document structure rather than interpreting arbitrary CSS. Fix: map content intentionally, or deliver the WeasyPrint PDF for visual fidelity and the DOCX as an editable companion.
Recommended Free Tools
Output is too large or slow
Fix: reduce image dimensions before embedding, choose an appropriate PDF/image DPI, limit pdf2image page ranges, cache stable assets, and process independent pages or jobs with bounded concurrency.
Best Value
- 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.
FAQ
Can WeasyPrint execute JavaScript?
Treat it as an HTML/CSS renderer, not a full browser runtime. Obtain content after application scripts run or use a browser-capable capture route.
Can I convert one HTML source to all three formats?
Yes, but use separate stages: WeasyPrint for PDF, pdf2image for raster pages, and a deliberate python-docx mapping for editable Word content.
Is a PDF page the same as an image?
No. A PDF can retain text and vector layout; rasterization produces fixed pixels whose dimensions depend on DPI.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteFrequently Asked Questions
Can WeasyPrint execute JavaScript?
Treat it as an HTML/CSS renderer, not a full browser runtime. Obtain content after application scripts run or use a browser-capable capture route.
Can I convert one HTML source to all three formats?
Yes, but use separate stages: WeasyPrint for PDF, pdf2image for raster pages, and a deliberate python-docx mapping for editable Word content.
Is a PDF page the same as an image?
No. A PDF can retain text and vector layout; rasterization produces fixed pixels whose dimensions depend on DPI.
Quick Recap
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.

