What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Generate the HTML in PHP, pass it to a PDF renderer, then stream the renderer’s bytes or save them to a controlled path. For conventional HTML and CSS, Dompdf is a practical PHP-only starting point. mPDF and tc-lib-pdf/TCPDF provide other PHP renderers, while a headless browser is a better fit when JavaScript or modern browser layout is essential. The correct choice depends on your template’s CSS, pagination, fonts, PHP runtime and resource-security requirements.
The basic architecture
PHP does not turn HTML into a paginated PDF by itself. Your application first creates HTML from a template and data. A renderer then parses that HTML, lays it out on pages and returns PDF bytes. You can send those bytes as an HTTP response for download or write them to an application-controlled file.
- Build a complete, representative HTML document from a template.
- Install and configure a renderer.
- Load the HTML with the correct character encoding.
- Set paper size and orientation when required.
- Render, then stream or save the output.
Keep template code separate from business logic. Test both short and long documents before relying on the result in production.
Generate a PDF with Dompdf
Dompdf is designed for mostly conventional HTML and a CSS 2.1-oriented subset. Its project documentation lists PHP 7.1 or higher, DOM and MBString extensions, php-font-lib and php-svg-lib, with GD used for image processing; confirm the requirements of the exact Composer release you install rather than copying an old minimum into deployment documentation. See the Dompdf README and project overview.
#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
1. Install the package
composer require dompdf/dompdf
2. Create and render the HTML
<?php
require __DIR__ . '/vendor/autoload.php';
use DompdfDompdf;
use DompdfOptions;
$options = new Options();
$options->set('isRemoteEnabled', false);
$options->set('chroot', __DIR__ . '/pdf-assets');
$dompdf = new Dompdf($options);
$html = '<h1>Invoice</h1><p>Generated from a PHP template.</p>';
$dompdf->loadHtml($html, 'UTF-8');
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream('invoice.pdf', ['Attachment' => true]);
This streams a download named invoice.pdf. To save instead, obtain the renderer’s output bytes and write them to a path your application controls:
$pdf = $dompdf->output();
$path = __DIR__ . '/var/pdf/invoice-' . $invoiceId . '.pdf';
file_put_contents($path, $pdf);
Ensure the destination directory exists and is not directly writable through user-supplied path segments. In a framework, return the bytes using that framework’s binary response helper.
Use a real template
<?php
ob_start();
include __DIR__ . '/templates/invoice.php'; // reads $invoice
$html = ob_get_clean();
$dompdf->loadHtml($html, 'UTF-8');
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream('invoice.pdf', ['Attachment' => true]);
Set an explicit UTF-8 meta declaration in the template and escape user-provided text. Keep CSS print-oriented: fixed widths, normal block flow, tables where appropriate, and explicit page-break rules.
Dompdf limitations that affect templates
- Dompdf does not support flexbox or CSS Grid. A browser-perfect layout can therefore collapse or reflow differently.
- Table cells are not pageable; a table row must fit on one page. Split very large records into smaller rows or use another renderer.
- Rendering occurs on the active page as elements are parsed, so document order and block sizing influence pagination.
- Fonts, long unbroken strings, large images and nested tables can create unexpected page breaks.
If your design depends on unsupported layout, simplify the print stylesheet or evaluate a different renderer instead of trying to patch every visual discrepancy.
Choosing a PHP PDF renderer
| Option | Useful when | Check before choosing |
|---|---|---|
| Dompdf | Conventional HTML/CSS and an in-process PHP renderer are sufficient. | CSS subset, table pagination, fonts, PHP extensions and resource restrictions. |
| mPDF | UTF-8 documents, headers, footers, page numbering, tables of contents or print-focused behavior matter. | Current PHP compatibility, CSS coverage, language and font behavior, and output quality for your template. Consult the mPDF manual. |
| tc-lib-pdf / TCPDF | A PHP PDF library with direct HTML/CSS rendering or documented PDF/UA structure mapping fits the project. | The project describes tc-lib-pdf as the current generation and states PHP 8.2+; verify the exact release and HTML/CSS scope in the HTML/CSS documentation and project site. |
| Headless browser through a PHP integration | JavaScript execution or browser layout is central to the page. | Browser binary and process deployment, resource loading, runtime cost and integration requirements. The TCPDF comparison lists Browsershot and Snappy in this category. |
There is no universal winner. Render the same representative templates through candidates and compare CSS fidelity, JavaScript needs, PHP compatibility, fonts, page breaks, headers and footers, operational dependencies and security controls.
When to use a headless browser
Choose browser-driven rendering when the page is assembled by JavaScript, relies on flexbox or Grid, uses web fonts that must match the browser, or contains components whose final content exists only after client-side execution. This approach adds a browser binary, process startup and deployment maintenance. It can also require explicit waits for network requests and JavaScript completion. If the document is static and print-oriented, a PHP renderer is usually simpler to operate.
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⁴
Assets, fonts and remote resources
Local files
Dompdf restricts local file access to configured chroot paths. Put approved images and fonts under a dedicated asset directory and reference them with predictable paths. Do not concatenate a user-provided filename into an asset path without validation.
Recommended Free Tools
Remote files
Remote resources are disabled in the example for a reason. Dompdf requires isRemoteEnabled plus cURL or allow_url_fopen for network resources. Enable it only when necessary, and allowlist hosts or proxy requests through a controlled service. User-influenced HTML can otherwise turn a PDF endpoint into a server-side request forgery or data-exfiltration surface.
Fonts and languages
Test every language you support, including non-Latin scripts, combining marks and right-to-left text. Register and package the required fonts according to the renderer’s documentation rather than assuming a browser-installed font exists on the server. Verify glyph coverage in the generated PDF, not just in an HTML preview.
Pagination and print CSS checklist
- Use print dimensions and margins that match the selected paper size.
- Keep table headers repeatable and avoid rows taller than a page.
- Use explicit page-break rules around major sections, but test their interaction with renderer pagination.
- Resize or compress oversized images before rendering.
- Provide fallback fonts and check line wrapping with long names, addresses and URLs.
- Generate both a small document and a worst-case long document during testing.
Troubleshooting common failures
“Class DompdfDompdf not found”
Composer’s autoloader was not included or dependencies were installed in a different directory. Run Composer in the application root and require vendor/autoload.php using an absolute project-relative path.
Images or CSS are missing
For local files, move assets under the configured chroot and use valid paths. For remote files, enable remote access only after confirming cURL or allow_url_fopen, TLS certificates and host policy. Inspect the generated HTML for malformed URLs.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problemsLayout differs from the browser
Check for flexbox, Grid, unsupported selectors, inherited styles and fixed-position elements. Replace unsupported layout with simpler blocks or tables, or move to a browser renderer.
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.
Rows split or disappear across pages
Dompdf cannot split a table row across pages. Break large records into smaller rows, reduce cell content, or choose a renderer whose pagination model fits the document.
Missing characters or boxes instead of text
The selected font lacks glyphs or was not embedded. Install and register a font with the needed script coverage, then regenerate and inspect the PDF on a machine without that font installed.
Timeouts or excessive memory use
Large images, huge tables and complex SVGs increase memory and render time. Reduce image dimensions, paginate data at the application level, remove unnecessary markup and set realistic PHP and worker limits. Browser rendering also adds process and browser startup overhead.
Operational and security practices
- Never render untrusted HTML with unrestricted network or filesystem access.
- Keep remote loading off by default and constrain local files with
chroot. - Use application-controlled filenames and directories for saved PDFs.
- Log renderer errors without exposing document contents or secrets.
- Pin and update Composer dependencies, then rerun visual regression tests after upgrades.
- Consider asynchronous jobs for large documents so web requests are not held open.
Or skip the browser setup
If you need a clean capture of a web page or generated HTML without deploying a browser, ScreenshotNeo provides a website screenshot API and MCP server. Its cleanup step accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups and chat widgets before capture; each step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP tools—take_screenshot, get_page_info and capture_pdf—work with Claude, Cursor and other MCP clients.
For a PDF capture, call the API endpoint with your URL and options as documented at ScreenshotNeo’s documentation. A simple screenshot request is:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
In PHP, you can call the same endpoint with cURL:
<?php
$url = 'https://api.screenshotneo.com/v1/shot';
$query = http_build_query([
'access_key' => 'YOUR_API_KEY',
'url' => 'https://stripe.com',
]);
$data = file_get_contents($url . '?' . $query);
file_put_contents(__DIR__ . '/shot.webp', $data);
ScreenshotNeo includes full-page capture, lazy-image loading, element selection, device and viewport controls, retina scale, PDF paper and margin settings, custom CSS and JavaScript, waits, request blocking, headers, cookies, authentication, timezone and geolocation, transparent backgrounds, resizing, caching, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, a usage API and an OpenAPI specification. Parameter names used by other screenshot APIs also work, easing migration.
The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing provides two months free, and every feature is included on every plan. Create a free ScreenshotNeo account.
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
FAQ
Can PHP generate a PDF without a library?
PHP can send a PDF file response, but it does not provide HTML layout and pagination. You need a renderer such as Dompdf, mPDF, tc-lib-pdf/TCPDF or a browser-based integration.
Should I use HTML tables for every PDF layout?
No. Use normal blocks for simple flow and tables for genuinely tabular data or when your chosen renderer handles them more predictably than modern layout features.
How do I decide between saving and streaming?
Stream when the user needs an immediate download. Save when another job, email process or later download needs a durable artifact; write only to an application-controlled directory.
Frequently Asked Questions
Can PHP generate a PDF without a library?
PHP can send a PDF response, but HTML layout and pagination require a renderer such as Dompdf, mPDF, tc-lib-pdf/TCPDF or a browser integration.
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 minuteWhat is the safest default for external images?
Keep remote loading disabled, store approved assets locally under the renderer’s allowed root, and enable network access only with an explicit host policy.
When is a headless browser worth its operational cost?
Use one when JavaScript execution or browser-only CSS is essential; otherwise a PHP renderer is generally simpler to deploy.
The Bottom Line
Start with Dompdf for conventional, trusted HTML and CSS; move to mPDF or tc-lib-pdf/TCPDF for their specific document features, and use a headless browser when you need actual browser behavior. Test long tables, fonts, pagination and resource loading before production.
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.
Free tools Windows power users keep installed
One-click scans. No signup required.

