PHP XHTML to PDF: Production API Guide for Developers
Learn PHP XHTML to PDF conversion with Chromium, libraries, APIs, code examples, and production fixes for fonts, pages, and security.
TL;DR
- PHP XHTML to PDF works best when the renderer matches your document needs: browser-based Chromium for modern CSS, WeasyPrint for controlled HTML/CSS, or a local library for small workloads.
- PDFGeny converts HTML, URLs, or templates through
POST https://pdfgeny.com/api/v1/render, with a median render time of 0.6 s and support for PDF/A-2b output through Ghostscript.
- Cold Chromium startup is a production failure mode: a cold headless browser costs about 7.8 s per request, while keeping Chromium warm brings rendering close to 0.65 s.
- wkhtmltopdf is not dead, but its maintenance status creates a CSS compatibility cost. For a handful of PDFs per day, a local library can still be the better engineering choice.
- PDFGeny provides a free plan with 50 documents a month, no card required. Get a free API key to send HTML, a URL, or a template and receive a PDF in one API call.
What is the best way to convert PHP XHTML to PDF?
PHP XHTML to PDF conversion is usually done with either a PHP PDF library or an external rendering service. A browser renderer such as headless Chromium is often the closest match to what users see in Chrome because XHTML, HTML5, CSS, JavaScript-generated layouts, and web fonts are handled by a real browser engine.
PDFGeny uses headless Chromium as its default engine, WeasyPrint as a second rendering engine, and Ghostscript for PDF/A-2b output. The API endpoint POST https://pdfgeny.com/api/v1/render accepts HTML, URLs, or one of 40 ready document templates and returns a finished PDF.
The engineering decision is not only about generating bytes. The difficult parts are page breaks, font loading, browser memory, security boundaries, and predictable output under load.
Key takeaway: PHP XHTML to PDF is a rendering problem before it is a file-format problem. The HTML/CSS engine determines most production failures.
PHP XHTML to PDF options: library, browser, or API?
The correct architecture depends on document volume, CSS requirements, and operational constraints. A developer generating five invoices per week has a different problem from a platform generating receipts continuously.
| Approach | Engine | Best fit | Main trade-off |
|---|---|---|---|
| Local PHP library | Library-specific renderer | Small document batches and offline systems | CSS support varies |
| Headless Chromium | Browser rendering | Modern HTML/CSS documents | Browser processes require memory management |
| PDF API | Managed Chromium or alternative engines | Applications that need predictable PDF infrastructure | External service dependency |
Failure mode: CSS compatibility breaks document layouts
wkhtmltopdf failures usually appear as missing CSS features, unexpected spacing, and layouts that differ from modern browsers. The issue is not that wkhtmltopdf cannot create PDFs. The issue is that many teams build HTML with current CSS assumptions and then discover their renderer has different capabilities.
wkhtmltopdf is not “dead”; the practical problem is that it is unmaintained. The real cost is the CSS it never learned. Teams that already have stable templates may have no reason to migrate, while new systems often choose Chromium because browser rendering matches frontend development workflows.
Failure mode: local rendering infrastructure becomes the product
A self-hosted Chromium setup requires browser binaries, sandbox configuration, memory limits, font packages, and monitoring. A PHP application that only needs invoices may spend more engineering time maintaining PDF infrastructure than building invoice logic.
PDFGeny removes that operational layer by exposing a render endpoint, async jobs, signed HMAC webhooks, and stored documents. Batch requests can include up to 100 documents in one call.
PHP XHTML to PDF with real production code
A PHP application can call a PDF generation API with a normal HTTP request. The following example uses cURL, which is available in most PHP production environments.
PHP example: send XHTML content to a PDF API
<?php
$payload = [
"html" => "<html><body><h1>Invoice #1001</h1><p>Amount: $120</p></body></html>"
];
$ch = curl_init("https://pdfgeny.com/api/v1/render");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
"Content-Type: application/json"
],
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_RETURNTRANSFER => true
]);
$response = curl_exec($ch);
if ($response === false) {
throw new Exception(curl_error($ch));
}
curl_close($ch);
file_put_contents("invoice.pdf", $response);
Failure mode: web fonts silently fall back
Web font failures are difficult because the PDF still generates. The document looks complete, but typography changes because the renderer finishes before the font loads.
The fix is not only adding a font URL. The rendering process must wait for fonts, verify availability, and avoid relying on browser timing. For controlled environments, bundling fonts or using a renderer with predictable font handling reduces surprises.
For developers comparing browser rendering approaches, the guide on Chrome HTML document to PDF production costs covers the operational side of browser-based conversion.
Production failures in PHP PDF rendering
Most PDF incidents are not caused by the final PDF file format. They happen earlier during rendering, networking, or resource loading.
Failure mode: cold Chromium startup increases latency
Headless Chromium performance depends heavily on process lifecycle. A cold browser costs about 7.8 s per request. Keeping Chromium warm reduces that startup cost and brings rendering close to 0.65 s.
This distinction matters for APIs and queues. Creating a new browser process for every invoice is different from maintaining a worker process that handles multiple renders.
Failure mode: Django async execution conflicts with Playwright
Python teams sometimes discover that running sync_playwright inside Django raises SynchronousOnlyOperation. The failure occurs because synchronous browser execution happens inside an async context.
The practical fix is moving the rendering operation onto its own thread or switching to an async-compatible implementation.
from threading import Thread
from playwright.sync_api import sync_playwright
result = {}
def render_pdf():
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.set_content("<h1>Invoice</h1>")
result["pdf"] = page.pdf()
browser.close()
thread = Thread(target=render_pdf)
thread.start()
thread.join()
with open("invoice.pdf", "wb") as file:
file.write(result["pdf"])
Failure mode: URL rendering creates an SSRF vulnerability
A URL-to-PDF endpoint can become a server-side request forgery entry point. A renderer that accepts arbitrary URLs may be tricked into accessing internal services, loopback addresses, private networks, or cloud metadata endpoints.
The security boundary must exist before rendering. Resolve the hostname, reject private and loopback IP ranges, block metadata addresses, and restrict outbound access.
For developers deciding between code and service approaches, the article PDF Generator API production costs and performance explains the infrastructure trade-offs.
What We Got Wrong / What Surprised Us
The strongest non-obvious conclusion is that an API is not always the right answer. A local library wins for a small number of documents per day because it removes network dependency, recurring API costs, and external service management.
The mistake teams often make is choosing based only on document count. A low-volume application with complex CSS may spend more time fighting renderer limitations than a higher-volume application using a managed API.
The surprising engineering detail is that browser startup dominates many rendering discussions. A renderer that produces a PDF in under a second after initialization can still feel slow if every request pays a multi-second browser startup cost.
PDFGeny's documented median render time is 0.6 s, but production architecture still depends on the surrounding workflow: template generation, asset loading, security checks, and storage.
Practical Takeaways
- Choose the renderer first. Spend 1-2 hours testing real templates with fonts, tables, and page breaks. Difficulty: Low. Expected outcome: fewer layout surprises.
- Measure startup separately from rendering. A Chromium cold start can cost about 7.8 s while a warm browser can render around 0.65 s. Spend 2-4 hours profiling. Difficulty: Medium. Expected outcome: correct latency decisions.
- Secure URL rendering before production. Add DNS resolution checks and reject private, loopback, and metadata addresses. Spend 1 day implementing controls. Difficulty: Medium. Expected outcome: reduced SSRF exposure.
- Pick local libraries for small workloads. If you only create a few PDFs daily, evaluate libraries before adding API infrastructure. Spend half a day comparing output. Difficulty: Low. Expected outcome: lower operational overhead.
- Move repeated templates into an API workflow. PDFGeny supports sync jobs, async jobs, signed HMAC webhooks, stored documents, and up to 100 documents per batch request. Spend 1-3 days integrating. Difficulty: Medium. Expected outcome: less PDF infrastructure code.
For applications that need HTML, URL, or template input with managed PDF rendering, PDFGeny provides a single API call workflow with a free plan of 50 documents per month.
FAQ: PHP XHTML to PDF
Can PHP convert XHTML to PDF without a browser?
Yes. PHP libraries can generate PDFs without Chromium. A local library is often the better choice for a small number of documents where CSS requirements are limited. Browser rendering becomes more useful when HTML must match modern frontend output.
Why do PHP HTML-to-PDF files have missing fonts?
Font failures usually happen because the renderer completes before web fonts finish loading. The PDF is created successfully, but fallback fonts replace the intended typeface.
Is wkhtmltopdf still suitable for PHP PDF generation?
wkhtmltopdf can still work for existing projects with stable templates. The concern is maintenance and CSS support, not that the tool suddenly stopped producing PDFs.
How much does PDFGeny cost?
PDFGeny provides a free plan with 50 documents per month and no card required. Overage pricing is $0.009 per document after the included documents are used.