Python PDF Generator: API vs Libraries for Production
Python PDF generator guide for developers: compare APIs and libraries, code examples, costs, failures, and production PDF rendering choices.
TL;DR
- Python PDF generators can be local libraries or hosted APIs. PDFGeny renders HTML, URLs, or templates through a POST request at
https://pdfgeny.com/api/v1/render, with a median render time of 0.6 s.
- Headless Chromium is the default PDFGeny engine, with WeasyPrint available as a second engine and Ghostscript used for PDF/A-2b output.
- Local libraries are often the right choice for a handful of PDFs per day; an API becomes more attractive when teams must maintain browsers, fonts, containers, queues, and security controls.
- Production failures are usually rendering failures: missing web fonts, incorrect page breaks, browser cold starts, memory growth, and SSRF risks from URL rendering.
- PDFGeny provides a free plan with 50 documents a month, no card required. Send HTML, a URL, or a template and receive a finished PDF back with Get a free API key.
What is a Python PDF generator, and which approach works?
A Python PDF generator converts structured data into a PDF document through a rendering engine or PDF library. The right choice depends on volume, document complexity, and operational requirements. A team generating three invoices per day may prefer ReportLab running inside a Python process, while a service generating invoices, receipts, certificates, and reports from multiple applications may prefer an API.
PDFGeny provides a hosted PDF generation API that accepts HTML, a URL, or one of 40 ready document templates. The API endpoint POST https://pdfgeny.com/api/v1/render returns a finished PDF without requiring an application team to operate Chromium infrastructure.
| Approach | Rendering model | Best fit | Main operational issue |
|---|---|---|---|
| Python PDF library | Runs inside your application | Small document workloads and offline generation | You maintain layout logic and dependencies |
| Headless Chromium service | Browser-based HTML rendering | Modern CSS, invoices, reports, branded documents | Browser memory and lifecycle management |
| Hosted PDF API | Remote rendering service | Applications needing predictable document delivery | External service dependency |
One useful contrarian observation: a hosted API is not automatically better. For a handful of documents a day, a local library beats an API because fewer moving parts exist. The calculation changes when PDF generation becomes a production subsystem with queues, retries, security reviews, and deployment concerns.
For developers comparing approaches, the difference is not only PDF output quality. It is ownership. A library gives maximum control; an API moves browser management, font installation, and renderer maintenance outside the application.
Python PDF generation with an API: a production example
The failure mode: browser lifecycle overhead. A cold headless Chromium process can cost about 7.8 s per request. Keeping the browser warm reduces that time to about 0.65 s, but maintaining a warm browser pool introduces another service to operate.
PDFGeny avoids requiring each application team to maintain that browser lifecycle. The Python integration is a normal HTTP request:
import requests
response = requests.post(
"https://pdfgeny.com/api/v1/render",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json",
},
json={
"html": """
<html>
<body>
<h1>Invoice #1042</h1>
<p>Amount due: $250</p>
</body>
</html>
""",
"format": "pdf"
},
)
response.raise_for_status()
with open("invoice.pdf", "wb") as file:
file.write(response.content)
The same API pattern works across backend stacks. PDFGeny's documentation shows examples for Python, Node.js, PHP, Go, Ruby, and cURL. The service supports sync and async jobs, signed HMAC webhooks, stored documents, and batch requests containing up to 100 documents in one call.
Production failures: the problems that break PDF generators
Failure mode: page breaks change after content grows
The failure mode: uncontrolled pagination. A document that looks correct with two invoice rows may split a table header from its rows after customer data increases.
HTML-to-PDF systems need explicit print CSS. A practical example:
<style>.invoice-table {
page-break-inside: avoid;
}
h2 {
break-after: avoid;
}
</style>
Chromium-based rendering handles modern CSS better than older HTML renderers, but page layout is still a browser print problem. Teams moving from older tools often discover that their HTML was designed for screens, not paper.
Failure mode: fonts silently fall back
The failure mode: font loading races. Web fonts can silently fall back when the renderer finishes before the font is available. The result is a PDF with changed line wrapping, different page counts, or missing brand typography.
A safer browser rendering flow waits for fonts:
await page.goto(url);
await page.evaluate(() => document.fonts.ready);
await page.pdf({path: "output.pdf"});
This problem is one reason hosted rendering systems must control browser timing, font availability, and document capture behavior.
Failure mode: URL rendering creates an SSRF vulnerability
The failure mode: server-side request forgery. A URL-to-PDF endpoint can become a path to internal services unless the application resolves hosts and rejects private, loopback, and metadata addresses before rendering.
Python applications implementing their own URL renderer need controls before opening a browser:
import socket
import ipaddress
from urllib.parse import urlparse
def allowed_url(url):
host = urlparse(url).hostname
ip = ipaddress.ip_address(socket.gethostbyname(host))
return not (
ip.is_private or
ip.is_loopback or
ip.is_link_local
)
print(allowed_url("https://example.com"))
Security is part of PDF generation because rendering a URL means your server fetches external content.
Python libraries versus APIs: when local wins
The failure mode: choosing an API for a problem that does not need one. A local PDF library can be the better engineering decision for small, predictable workloads.
| Requirement | Local Python library | PDFGeny API |
|---|---|---|
| Daily output | Good for small volumes | Designed for application workflows |
| HTML and CSS rendering | Depends on renderer | Chromium default engine |
| Batch creation | Build yourself | Up to 100 documents per call |
| Document templates | Create and maintain templates | 40 ready document templates |
| Compliance output | Configure tools yourself | PDF/A-2b output support |
Developers evaluating ReportLab should understand the trade-off. ReportLab excels when documents are programmatically drawn and tightly controlled. HTML rendering is different: the browser becomes the layout engine.
For more detail on this distinction, see the guide on ReportLab PDF generation API vs library choices and the production considerations in Python PDF library production API guidance.
What We Got Wrong / What Surprised Us
The strongest non-obvious lesson is that PDF generation failures rarely start with PDF syntax. They start with infrastructure boundaries.
The surprising failure mode: framework integration problems. Running sync_playwright inside Django can raise SynchronousOnlyOperation unless rendering happens on its own thread. A browser automation library may work perfectly in a script and fail inside an async web framework.
Another common mistake is treating wkhtmltopdf migration as a simple binary replacement. The issue is not that wkhtmltopdf is “dead”; the issue is that it is unmaintained. The real cost is the CSS it never learned, especially as teams move toward modern web layouts.
The practical conclusion from these failures is simple: PDF generation is a rendering system, not just a file export feature.
Practical Takeaways
- Choose your rendering model first. Spend 30-60 minutes reviewing whether your documents are HTML-driven or programmatically drawn. Difficulty: Easy. Expected outcome: fewer rewrites between libraries and browser renderers.
- Test fonts and page breaks with real documents. Spend 1-2 hours creating invoices, reports, and long tables. Difficulty: Medium. Expected outcome: fewer production layout surprises.
- Secure every URL renderer. Spend 2-4 hours adding host validation and network restrictions. Difficulty: Medium. Expected outcome: reduced SSRF exposure.
- Measure browser startup cost. Spend half a day profiling cold and warm rendering. Difficulty: Medium. Expected outcome: clearer infrastructure decisions.
- Move to an API when PDF generation becomes operational work. Spend 1-3 days replacing custom browser management with an API integration. Difficulty: Medium. Expected outcome: fewer deployment dependencies.
Try PDFGeny for application PDF generation
PDFGeny is designed for teams that need application documents without operating a Chromium container, managing fonts, or maintaining renderer processes. The API accepts HTML, URLs, or templates and returns PDFs through a single request. The free plan includes 50 documents a month with no card required.
Send HTML, a URL, or a template and get a finished PDF back from your application without running your own browser infrastructure.
FAQ: Python PDF generator questions
Is Python good for generating PDFs?
Yes. Python supports libraries for direct PDF creation and HTTP clients for hosted rendering APIs. The best option depends on whether your documents require browser-style HTML rendering or programmatic drawing.
What is the fastest way to generate PDFs from Python?
A hosted rendering API can avoid local browser startup and maintenance work. PDFGeny reports a median render time of 0.6 s for its rendering service.
Should I use ReportLab or a PDF API?
ReportLab is often better for small workloads with strict programmatic layouts. A PDF API is usually a better fit when teams need HTML rendering, templates, batch processing, webhooks, or managed browser infrastructure.
Why do generated PDFs look different from HTML pages?
PDF rendering introduces print-specific behavior. Fonts, page breaks, CSS support, and browser timing all affect the final file. Testing with production-sized documents is required before shipping.