Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
To export HTML to PDF in PHP, install a Composer-based renderer, build a complete and sanitized HTML document, render it, then stream or save the returned PDF bytes. Use Dompdf for straightforward CSS 2.1-style invoices and reports, mPDF for UTF-8 business documents with pagination features, tc-lib-pdf when you need the current TCPDF generation on PHP 8.2+, and a Chromium-backed renderer when modern CSS or JavaScript must match a browser.
Choose the rendering approach first
PHP is the host language; the PDF engine determines how much of your HTML, CSS, JavaScript, fonts and layout will work. Decide based on the document rather than choosing the most familiar package.
| Option | Best fit | Compatibility and trade-offs |
|---|---|---|
| Dompdf 3.1 | Invoices, receipts and simple reports | CSS 2.1-oriented PHP renderer; low deployment overhead. The comparison lists PHP ^7.1 || ^8.0. |
| mPDF 8.3 | UTF-8 business documents | HTML/CSS workflow with headers, footers, page numbers, tables of contents, barcodes and color handling. The comparison lists support from PHP ^5.6 through approximately 8.5. |
| tc-lib-pdf 8.73 (current TCPDF generation) | Explicit PDF controls, HTML/CSS/SVG and accessibility-oriented output | Pure PHP, Composer-installed, and requires PHP ^8.2. The project describes it as the current generation of TCPDF. |
| Chromium-backed rendering | Modern web layouts, JavaScript and browser-level CSS fidelity | Adds Node/Puppeteer, a Chromium binary, or a service. Output can change when the browser runtime changes. |
The TCPDF comparison also identifies Browsershot (Chromium through Node/Puppeteer), Snappy (the wkhtmltopdf binary) and Gotenberg (a Chromium/LibreOffice service). wkhtmltopdf was archived upstream in January 2023 and uses an older Qt WebKit engine, so it is a poor default for new modern-CSS work.
Common prerequisites
- PHP and Composer available in the application environment.
- A server-side template that produces a complete document, including character encoding and print styles.
- Fonts installed or bundled on the server for every language and symbol you output.
- A response path that emits only PDF bytes—no warnings, debug toolbar, whitespace or accidental BOM before headers.
- A policy for images, stylesheets and other remote resources. External fetching should be disabled unless the document genuinely needs it.
Export an invoice with Dompdf
Install the package
composer require dompdf/dompdf
Render and download
<?php
require __DIR__ . '/vendor/autoload.php';
use DompdfDompdf;
use DompdfOptions;
function e(string $value): string {
return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
$data = [
'number' => 'INV-1042',
'customer' => 'Ada Lovelace',
'total' => '249.00',
];
$html = '<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
@page { size: A4; margin: 18mm; }
body { font-family: DejaVu Sans, sans-serif; font-size: 11pt; color: #222; }
h1 { font-size: 20pt; }
table { width: 100%; border-collapse: collapse; }
th, td { border-bottom: 1px solid #ccc; padding: 6pt; text-align: left; }
</style>
</head>
<body>
<h1>Invoice ' . e($data['number']) . '</h1>
<p>Customer: ' . e($data['customer']) . '</p>
<p>Total: €' . e($data['total']) . '</p>
</body>
</html>';
$options = new Options();
$options->setIsHtml5ParserEnabled(true);
// Keep this false unless you have a tightly controlled, necessary remote asset policy.
$options->setIsRemoteEnabled(false);
$dompdf = new Dompdf($options);
$dompdf->loadHtml($html, 'UTF-8');
$dompdf->setPaper('A4');
$dompdf->render();
$dompdf->stream('invoice-' . $data['number'] . '.pdf', ['Attachment' => true]);
The HTML5 parser accepts more tolerant markup. Configure a filesystem chroot when local assets are allowed, and keep remote URL loading scoped. For inline or bundled fonts, verify that the selected font contains every required glyph.
#1 Best Overall
- INNOVATIVE CARTRIDGE-FREE PRINTING — No more dealing with lots of tiny ink cartridges; With this wireless document and photo printer each ink bottle set is equivalent to about 90 individual cartridges²
- LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; When you choose this combination printer, scanner and copier you can print up to 4,500 pages black/7,500 color³
- COLOR PRINTING — Up to 2 years of ink in the box4 (and with every replacement ink set) for fewer out-of-ink frustrations
- ZERO CARTRIDGE WASTE — By using an Epson EcoTank printer you can help reduce the amount of cartridge waste ending up in landfills
- HOME PRINTER DESIGNED FOR RELIABILITY — The Epson EcoTank ET-2800 All-in-One Supertank Color Printer creates vivid, detailed prints and documents thanks to Micro Piezo Heat-Free Technology; Fire off 10 ISO pages per minute1 to easily finish large jobs
Generate business PDFs with mPDF
Install and output
composer require mpdf/mpdf
<?php
require __DIR__ . '/vendor/autoload.php';
use MpdfMpdf;
$html = render_invoice_template($data); // escape and validate every user value
$mpdf = new Mpdf([
'format' => 'A4',
'tempDir' => __DIR__ . '/var/mpdf',
]);
$mpdf->WriteHTML($html);
$mpdf->Output('invoice.pdf', MpdfOutputDestination::DOWNLOAD);
mPDF is designed around UTF-8 HTML. Its manual recommends writing the document as HTML/CSS and passing that markup to mPDF, which lets you develop much of the layout in a browser. Use its header, footer, page-number, table-of-contents and barcode facilities when those are more important than browser-perfect CSS. Sanitize input more strictly than ordinary browser output because PDF generation can fetch resources and process markup.
Use tc-lib-pdf for the current TCPDF generation
tc-lib-pdf is the current TCPDF generation: a pure-PHP PDF library for PHP 8.2 and later, split into focused Composer packages. The comparison lists HTML, CSS and SVG rendering, while its HTML/CSS documentation describes tagged output and PDF/UA-oriented controls such as heading structure and alternate text.
When it is the right choice
- Your production runtime is PHP 8.2 or newer.
- You need explicit control over PDF structure, tags, SVG or accessibility-oriented metadata.
- You prefer a pure-PHP deployment rather than operating Chromium.
Implementation
Install the package specified by the project for your required modules, then follow its Composer setup to create the document and either return the generated bytes or stream them from the controller. Keep the response free of incidental output and set a meaningful download filename. Unlike the compact Dompdf example, tc-lib-pdf APIs are split across focused packages, so pin the package versions and follow the matching project API for your installed release.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
When a browser-backed renderer is better
Choose Chromium when the source page depends on current flexbox or grid behavior, web fonts, JavaScript-generated content, charts, or the same layout users see in a browser. Browsershot requires Node/Puppeteer and Chromium; Snappy requires the wkhtmltopdf binary; Gotenberg requires a separately operated Chromium/LibreOffice service.
- Deployment: package and patch the external runtime separately from PHP.
- Reproducibility: pin the browser or service version because rendering changes between engine releases.
- Reliability: allocate process timeouts, memory limits and a queue for large jobs.
- Security: isolate untrusted pages and restrict network access, filesystem access and navigation targets.
Prepare HTML that survives PDF pagination
- Start with a complete document:
doctype,html, language, UTF-8meta, CSS and body. - Escape text with context-appropriate encoding. Sanitize any permitted HTML separately; escaping a whole trusted template is not a substitute for validating user input.
- Use print-oriented CSS: explicit page size and margins, predictable widths, table headers, and deliberate page-break rules.
- Prefer local, versioned assets. If remote images or styles are necessary, allow-list hosts and protocols and set timeouts.
- Register the exact fonts needed for multilingual output and test real glyphs, not only ASCII samples.
- Keep data and templates separate so a malformed value cannot close a tag or inject CSS.
Stream versus save
Streaming is appropriate for an interactive download; saving is better for queued jobs, audit trails or later email delivery. In either case, render first, check for errors, and send the correct Content-Type: application/pdf and filename. Never print diagnostics before the PDF. For large reports, generate in a worker and return a status or download URL rather than holding an HTTP request open.
Rank #2
- CARTRIDGE-FREE PRINTING — Print lab-quality photos, graphics and creative projects; Get vibrant colors and sharp text with Epson's high-accuracy printhead and Claria ET Premium 6-color inks
- INK BOTTLES — Save on photos1 and creative projects with affordable in-house printing; All-in-one printer allows you to print 4" x 6" photos for about 4 cents each vs. 40 cents with traditional ink cartridges1
- LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; Printer, scanner and copier lets you print up to 6,200 color pages³
- PRINT FOR LONGER — Up to 2 years of ink in the box² (and with every replacement ink set) for fewer out-of-ink frustrations with this wireless printer
- ZERO CARTRIDGE WASTE — Epson EcoTank printer helps reduce the amount of cartridge waste ending up in landfills; Cartridge-free printer uses high-yield ink bottles; Each replacement ink bottle set is equivalent to about 100 individual ink cartridges⁴
Security, reliability and performance checklist
- Input: escape or sanitize every user-controlled value.
- Network: disable remote loading by default; if required, restrict hosts, schemes and redirects to reduce server-side request risks.
- Filesystem: set Dompdf’s
chrootor the equivalent boundary and expose only an asset directory. - Fonts: embed and register known font files; missing glyphs often appear as boxes or blank text.
- Versions: pin Composer dependencies and any Node, Chromium, wkhtmltopdf or Gotenberg runtime.
- Memory: reduce image dimensions, paginate large datasets and queue browser jobs. Rendering a very long HTML table can consume substantially more memory than the source data.
- Regression testing: keep representative PDFs and inspect page breaks, image loading, font embedding, Unicode text and accessibility metadata after upgrades.
Troubleshoot the failures developers see most
Blank or partially rendered PDF
Malformed HTML, an exception hidden by the download response, unsupported CSS or a resource timeout are common causes. Log renderer errors before streaming, validate the generated HTML, and test with external resources disabled.
Images do not appear
Check path resolution, MIME type and permissions. For remote images, confirm that the renderer permits remote loading and that the host is allow-listed. Prefer a local asset or a data URI for a small, trusted image.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchPC 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 & 11Boxes replace accented or Asian characters
The server font lacks those glyphs or was not embedded. Install/register a font with coverage for the target script, then verify the resulting PDF rather than relying on the browser preview.
CSS looks different from the website
Dompdf and mPDF are not full browser engines. Simplify to supported print CSS or move the job to Chromium. If output changes after an upgrade, compare the pinned renderer versions and update regression fixtures.
Headers are already sent
A warning, debug statement, BOM or stray whitespace preceded the PDF. Remove output before the controller response, disable display errors for production downloads, and log diagnostics instead.
Rank #3
- SET IT UP ONCE AND PRINT WITH CONFIDENCE. No complicated maintenance. Just easy, reliable printing you can count on.
- INK FOR YEARS. NOT MONTHS. Up to 2 years of ink included. Get thousands of pages of cartridge-free printing. More pages, less hassle
- KEEPS PRINTING WELL AFTER COMPETITORS HAVE QUIT. No complex maintenance. Sharper text, richer colors.[2] Only with HP Smart Tank
- PREMIUM SUPPORT - Strong technical expertise to solve issues faster
- THE LAST PRINTER YOU'LL EVER NEED. Enjoy years of refillable, cartridge-free printing.
Jobs time out or exhaust memory
Lower image resolution, split very large reports, cache stable assets and run generation asynchronously. Browser-backed jobs also need explicit process and navigation timeouts.
Or skip the browser setup
ScreenshotNeo is a website screenshot API and MCP server when you need a rendered page or PDF without installing a browser in your PHP application. One GET request returns PNG, JPEG, WebP or PDF bytes. Before capture it accepts the cookie/consent banner like a visitor 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.
cURL
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
PHP
<?php
$url = 'https://api.screenshotneo.com/v1/shot';
$query = http_build_query([
'access_key' => 'YOUR_API_KEY',
'url' => 'https://stripe.com',
]);
$context = stream_context_create(['http' => ['timeout' => 90]]);
$pdfOrImage = file_get_contents($url . '?' . $query, false, $context);
if ($pdfOrImage === false) {
throw new RuntimeException('Screenshot request failed');
}
file_put_contents(__DIR__ . '/shot.webp', $pdfOrImage);
Python
import 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)
Node.js
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}`);
require('node:fs').writeFileSync('shot.webp', Buffer.from(await res.arrayBuffer()));
For parameters, PDF options, signed links, asynchronous jobs, bulk capture and the MCP tools take_screenshot, get_page_info and capture_pdf, see the ScreenshotNeo documentation. The MCP server works with Claude, Cursor and other MCP clients. Every feature is on every plan: 1,000 screenshots per month are free with no card; paid plans start at $5 for 3,000, with yearly billing providing two months free.
Sign up for the free ScreenshotNeo plan to try 1,000 screenshots a month without a card.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Decision guide
- Pick Dompdf for the simplest low-dependency invoice or report.
- Pick mPDF for UTF-8 HTML documents where headers, footers, page numbers, contents and barcodes matter.
- Pick tc-lib-pdf for PHP 8.2+ projects needing current TCPDF-family controls, HTML/CSS/SVG or tagged output.
- Pick Chromium when JavaScript and modern browser layout are non-negotiable and you can operate the additional runtime.
- Use ScreenshotNeo when an API or MCP workflow is preferable to maintaining browser infrastructure and you want failed or unclean captures excluded from billing.
FAQ
Can PHP convert HTML to PDF without JavaScript?
Yes. Dompdf, mPDF and tc-lib-pdf render server-side HTML without requiring a browser. They are suitable when the final document does not depend on client-side JavaScript.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Which option is most portable across hosting providers?
A Composer-installed pure-PHP library generally avoids installing Node, Chromium or a system binary. Confirm the library’s PHP requirement and your host’s memory and filesystem limits before deployment.
Rank #4
- Wireless Bluetooth Printer: Portable thermal printer compatible with iPhone, Android phones, iPad and tablet computers via Bluetooth. For smartphones, please download the "Nada Print" App. You can also connect to laptops and computers for printing using a USB-C cable. (Note: Laptops and computers can only be connected via USB and require the installation of a driver first. Bluetooth connection is not supported.)
- No-ink printing: Only supports US Letter and A4 size thermal paper.(Doesn't support regular paper) The no-ink portable thermal printer uses direct thermal technology, requiring no ink, toner or ribbons, making it environmentally friendly, cost-effective and time-saving. The thermal printer package comes with a roll of US Letter thermal printing paper. Note: When installing the paper, remember to switch the paper size switch on APP
- Clear Print: NDYIN N80 portable thermal printer adopts high-definition printing technology, with a 203DPI resolution to provide you with clear printing results. This mobile printer is compatible with roll paper, folded paper and tattoo transfer paper, supporting printing from your mobile phone PDF, Word, pictures and web pages anytime and anywhere. It is recommended to use our NDYIN thermal paper to achieve good printing quality
- Portable wireless printer for travel: The thermal printer is equipped with a built-in 1500mAh rechargeable battery, which can print 160 sheets of 8.5" x 11" thermal paper after being fully charged. It weighs only 1.5 pounds and is compact in size. This ink-free portable printer can be easily carried in a backpack or briefcase! It is perfect for business travel, cars, small offices, construction sites, schools and homes. You can print documents, contracts, invoices and boarding passes anytime and anywhere
- The N80 thermal printer has a wide range of uses. The package includes the N80 printer, a roll of US Letter paper(7m/roll), a user manual, a guide card, a type-C soft cable and a type C adapter. Note: The charging adapter is not included. Special thermal paper is required for use; ordinary paper cannot be used. This ink-free portable thermal printer is suitable for various scenarios such as home, school, travel, office, and outdoor, meeting the printing needs of different groups of people. This tattoo template printer is also compatible with tattoo transfer paper, making it an ideal choice for tattoo art
Should I reuse my website’s CSS?
Reuse only the rules your chosen renderer supports. A dedicated print stylesheet is usually more predictable than sending a full application bundle to a PDF engine.
Frequently Asked Questions
Can a PDF be generated from a URL instead of a local template?
Yes. A browser-backed service such as ScreenshotNeo can capture a public URL directly; a local PHP library normally receives HTML that your application has rendered.
How do I make generated PDFs reproducible?
Pin Composer packages, fonts and any browser or service runtime, then retain representative PDF fixtures and inspect them after upgrades.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →The Bottom Line
Use a Composer renderer for controlled server-side documents, Chromium when browser fidelity is essential, and ScreenshotNeo when you want a maintained screenshot/PDF API and MCP workflow without operating the browser runtime.
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.

