Tutorials

PHP PDF Generation: APIs, Libraries, and Production Fixes

Learn PHP PDF generation with runnable API code, library comparisons, real rendering costs, security fixes, and practical production advice.

M Mikel Rougstone · 28 November 2026 · 10 min read
PHP PDF Generation: APIs, Libraries, and Production Fixes

TL;DR

  • PHP PDF generation works best when you choose a rendering method based on document complexity, volume, and operational constraints. A local library is often the simplest option for a handful of documents per day.
  • PDFGeny accepts HTML, a URL, or one of 40 ready document templates through a single API endpoint. Its default renderer is headless Chromium, with WeasyPrint as a second engine and Ghostscript for PDF/A-2b output.
  • Performance: PDFGeny reports a median render time of 0.6 seconds. A cold headless Chromium process can cost about 7.8 seconds per request, compared with approximately 0.65 seconds when the browser stays warm.
  • Pricing: PDFGeny's free plan includes 50 documents per month without a credit card. Additional documents cost $0.009 each, making 1,000 overage documents $9 before any other applicable charges.
  • Production risks: PHP PDF generation can fail through missing web fonts, incorrect page breaks, memory pressure, and server-side request forgery (SSRF). Fix these failure modes before scaling traffic.

PHP PDF generation means turning application data, HTML, or structured document definitions into a portable PDF file. PHP developers can use a local library such as Dompdf, mPDF, or TCPDF, run a browser renderer such as Chromium, or call a hosted API. PDFGeny exposes a single rendering endpoint, POST https://pdfgeny.com/api/v1/render, and reports a median render time of 0.6 seconds. The right choice depends on how accurately the document must reproduce HTML and CSS, how much infrastructure the application can maintain, and whether generation needs to happen synchronously or in the background.

1. Choose the Right PHP PDF Generation Method

PHP PDF libraries and browser-based renderers solve different problems. A library may draw text, tables, and images directly into a PDF without running a browser. Chromium renders HTML and CSS using a browser layout engine, which is often preferable for invoices, reports, and certificates that already exist as web templates.

MethodBest fitMain trade-off
DompdfHTML invoices and straightforward reportsCSS support differs from a modern browser.
mPDFHTML documents requiring features such as complex text handlingBrowser CSS compatibility is not its primary design goal.
TCPDFProgrammatic layouts and controlled PDF drawingComplex layouts may require more manual positioning.
Local Chromium or PuppeteerHTML and CSS that depend on browser renderingBrowser installation, lifecycle, memory, and concurrency become application concerns.
PDFGeny APIApplications that prefer a hosted rendering serviceRequires network access, credentials, and a provider dependency.

When a local library wins

A local library is usually the better choice for a handful of documents per day when the layout is simple, the existing PHP runtime can handle rendering, and external dependencies are undesirable. A hosted API introduces a network request, another service boundary, and potentially another place where sensitive document content is processed.

For a document with fixed columns, a logo, and several lines of text, drawing directly into a PDF can be easier to control than rendering a full HTML page. For a branded invoice with reusable CSS, web fonts, and responsive components, browser-based rendering may reduce layout translation work.

Developers evaluating alternatives can compare implementation approaches in this guide to PHP XHTML-to-PDF generation. The key variable is not the programming language: it is the amount of HTML and CSS behavior the document needs to preserve.

2. Generate a PDF from PHP with an API

PDFGeny's rendering endpoint accepts a JSON request containing a rendering input and returns a generated document. The following PHP example demonstrates the HTTP integration pattern using PHP's cURL extension. It assumes an API key and a request schema with an html field; confirm the current authentication header, response format, and required fields against the provider's API documentation before deployment.

Runnable PHP HTTP client

<?php
declare(strict_types=1);

$apiKey = getenv('PDFGENY_API_KEY');

if (!$apiKey) {
    throw new RuntimeException('PDFGENY_API_KEY is not configured');
}

$html = '<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    body { font: 12pt Arial, sans-serif; margin: 32px; }
    h1 { color: #183153; }
  </style>
</head>
<body>
  <h1>Invoice INV-1042</h1>
  <p>Amount due: $125.00</p>
</body>
</html>';

$payload = json_encode(
    ['html' => $html],
    JSON_THROW_ON_ERROR
);

$ch = curl_init('https://pdfgeny.com/api/v1/render');

curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer '. $apiKey,
        'Content-Type: application/json',
        'Accept: application/pdf',
    ],
    CURLOPT_POSTFIELDS => $payload,
]);

$response = curl_exec($ch);

if ($response === false) {
    $error = curl_error($ch);
    curl_close($ch);
    throw new RuntimeException('PDF request failed: '. $error);
}

$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
curl_close($ch);

if ($status < 200 || $status >= 300) {
    throw new RuntimeException(
        "PDF API returned HTTP status {$status}"
    );
}

if (!is_string($contentType) ||
    stripos($contentType, 'application/pdf')!== 0 ||!str_starts_with($response, '%PDF-')
) {
    throw new RuntimeException('Response is not a PDF document');
}

if (file_put_contents('invoice-1042.pdf', $response) === false) {
    throw new RuntimeException('Could not save the PDF');
}

echo "PDF saved successfully\n";

Integration caveat: The code is runnable as a PHP cURL client, but the example's Bearer authentication, html payload, and raw-PDF response are assumptions that must match the API's documented contract. An endpoint URL alone does not establish those details. If the service returns JSON containing a document URL or job identifier instead, adapt the response handling rather than saving the JSON as a PDF.

Why response validation matters

Failure mode: an HTTP request succeeds but produces an unusable file. A proxy error, authentication failure, or asynchronous job response may contain valid HTTP content that is not a PDF. Check the HTTP status, content type, and PDF signature before saving the response. For asynchronous jobs, persist the job identifier and retrieve the finished document using the documented status or download endpoint.

PDFGeny supports synchronous and asynchronous jobs, signed webhooks using HMAC, and stored documents. Those capabilities allow a PHP application to choose between waiting for a result during a request and handing longer-running work to a background workflow.

For an existing browser-rendering implementation, the Puppeteer PDF production guide explains the operational considerations behind keeping a renderer in production.

PDFGeny offers a hosted alternative when maintaining a browser runtime is more work than the document-generation feature itself. Its free plan covers 50 documents per month, with no credit card required.

Get a free API key

3. Fix the Production Failures Before Increasing Volume

PDF generation failures often originate in the rendering environment rather than in PHP itself. A request can execute without throwing an exception and still produce a document with missing fonts, clipped content, or an unsafe external resource request.

Failure mode: cold Chromium processes inflate latency

A cold headless Chromium process costs about 7.8 seconds per request in the supplied project data. Keeping the browser warm brings that figure to approximately 0.65 seconds. The difference comes from browser startup and initialization, not simply from the speed of the PDF-writing operation.

Fix: If you operate Chromium yourself, reuse a browser process where the rendering library permits it, isolate individual pages or contexts, and recycle the browser under controlled conditions. Do not assume a single browser can safely handle unlimited concurrent jobs. Track browser crashes, memory usage, queue length, and render duration separately.

PDFGeny's reported median render time is 0.6 seconds, but a median is not a guarantee for every document. Large images, remote resources, complicated layouts, and unusually long reports can take longer. Benchmark with representative documents and examine tail latency before setting application timeouts.

Failure mode: web fonts silently fall back

A PDF may contain valid text but use the wrong typeface because the renderer finishes before a web font has loaded. The result can change line wrapping, move totals onto another page, or clip a heading that fitted in the browser preview.

Fix: Wait for fonts explicitly in browser-based rendering. With Puppeteer, for example, call await page.evaluate(() => document.fonts.ready) before creating the PDF. Also verify that font URLs are reachable from the renderer, that cross-origin rules permit loading, and that the font files can be embedded where required.

Failure mode: page breaks split important content

Browser print layout does not automatically keep every invoice row, signature block, or heading together. A screen layout that looks correct can paginate differently when converted to paper-sized pages.

Fix: Set an explicit page size and margins, then apply print CSS such as break-inside: avoid to small logical blocks and break-before: page where a new page is required. Avoid wrapping a large table or an entire report in an unbreakable container; the renderer may create excessive whitespace or overflow.

Test documents with unusually long customer names, large line-item tables, empty optional fields, and multiple pages. These inputs reveal layout defects that a short sample invoice will miss.

Failure mode: URL rendering exposes internal services

A URL-to-PDF endpoint can become a server-side request forgery (SSRF) vulnerability if an attacker controls the destination. A renderer that can access loopback interfaces, private network hosts, or cloud metadata addresses may fetch resources that were never intended to be public.

Fix: Resolve the hostname, reject private, loopback, link-local, and metadata addresses, and validate every redirect. Account for DNS rebinding by enforcing destination checks at connection time, not only during initial validation. Restrict outbound network access as a second layer of defense.

Never treat a URL allowlist check performed only in PHP as a complete defense if the actual renderer can resolve the hostname differently. A hosted service also needs appropriate controls around URLs and fetched resources; outsourcing rendering does not remove the need to understand its security model.

4. Challenge the Assumption That Every PDF Needs an API

The common instinct to replace a troublesome local renderer with a hosted service is not always correct. For a few predictable documents per day, a PHP library can avoid network latency, API credentials, provider outages, and per-document charges. If the PDF contains only simple text and tables, introducing a remote rendering dependency may add more failure modes than it removes.

Compare the real operating costs

OptionKnown cost or limitWhat to account for
PDFGeny free plan50 documents per month; no card requiredAPI integration, data handling, and plan limits.
PDFGeny overage$0.009 per documentAt 1,000 overage documents, the document charge is $9.
Local PHP libraryNo PDFGeny per-document chargeDeveloper time, dependency maintenance, and rendering constraints.
Self-hosted ChromiumNo hosted API charge for renderingCompute, browser updates, memory, monitoring, scaling, and incident response.

The variable that changes this decision is operational ownership. A local library has a low marginal infrastructure cost when the existing application server has spare capacity. A Chromium service can become expensive in engineering time if the team must manage process pools, sandboxing, font packages, browser upgrades, and concurrency limits.

PDFGeny supports PDF/A-2b output through Ghostscript, alongside Chromium as its default engine and WeasyPrint as a second engine. PDF/A-2b can help with long-term document preservation requirements, but selecting the format alone does not establish legal compliance or guarantee that every source document is suitable for archival use.

Why an older renderer can still be a bad fit

wkhtmltopdf is unmaintained, not simply obsolete. Existing deployments can continue to work, especially when their templates rely on stable legacy behavior. The more significant cost is often the CSS the renderer never learned: developers may need special markup, layout workarounds, and template-specific exceptions to reproduce a modern browser design.

Replacing it is not automatically a win. Existing output can change when a different renderer interprets fonts, tables, margins, or page breaks differently. Keep a representative collection of PDFs and compare text, pagination, and visual output before switching engines. The guide to wkhtmltopdf's maintenance and compatibility costs provides more context for that decision.

5. What We Got Wrong / What Surprised Us

The most useful lesson is that PDF generation speed is often a lifecycle problem, not a language problem. PHP does not need to be intrinsically slow for PDF generation to take several seconds: waiting for a cold browser to start can dominate the request. The supplied comparison between 7.8 seconds cold and approximately 0.65 seconds warm makes browser lifecycle a first-class architectural concern.

A second non-obvious point is that faster rendering does not always mean a better document pipeline. A renderer that returns quickly but silently substitutes a font can produce a PDF that is technically valid and visually wrong. Correct font loading, pagination, and output validation should be treated as acceptance criteria alongside latency.

Django users encounter a related integration issue: calling synchronous Playwright code inside an asynchronous execution context can raise SynchronousOnlyOperation. The failure comes from crossing Django's synchronous/asynchronous boundary, not from PDF itself. Move the synchronous rendering operation onto an appropriate worker thread or use a compatible asynchronous design rather than suppressing the exception.

One limitation deserves equal attention: a hosted API cannot make an unsafe template safe, repair inconsistent business data, or guarantee identical output across every rendering engine. Rendering infrastructure and document correctness are separate responsibilities.

6. Practical Takeaways

  • Inventory your documents. Spend 30–60 minutes listing document types, page sizes, font requirements, and expected daily volume. Difficulty: easy. Expected outcome: a clear shortlist of documents that need browser rendering and those a local library can handle.
  • Build a representative test set. Spend 1–3 hours creating sample invoices, long reports, multi-page tables, and documents with optional fields. Difficulty: moderate. Expected outcome: repeatable checks for pagination, fonts, and content overflow.
  • Validate the integration contract. Spend 30–90 minutes checking API authentication, request fields, synchronous versus asynchronous responses, and error handling. Difficulty: moderate. Expected outcome: PHP code that distinguishes a real PDF from an error response or job identifier.

Measure the complete rendering path. Spend 1–2 hours recording request latency, render duration, memory usage, and timeout frequency. Difficulty: moderate. Expected outcome:

M

Mikel Rougstone

Founder, PDFGeny

I build and run PDFGeny — the API, the rendering fleet and the template catalog. Most of what I write here comes from something that broke in production first.