Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To include JavaScript-generated content in a PDF, render the HTML string in a browser engine such as Chrome or Chromium, wait until the page’s scripts and required assets are ready, and then print the page to PDF. A PHP HTML-to-PDF library that only lays out HTML and CSS will not run the JavaScript: Dompdf explicitly does not execute it. For a self-hosted PHP workflow, chrome-php/chrome controls a local browser; a hosted Chrome service is an option when you cannot operate Chromium yourself.

Why the renderer matters

An HTML string is only the starting document. JavaScript can change the DOM, fetch data, render a chart, or populate a template after the initial markup loads. To include those changes, the PDF renderer must execute JavaScript and wait for the resulting page state before printing.

Dompdf accepts HTML through loadHtml(), but its official tutorial says it does not run JavaScript. It is therefore suitable when your document is already represented by static HTML and CSS, not when the desired output depends on browser scripts. mPDF likewise accepts an HTML string through WriteHTML(), but its manual recommends headless Chrome for modern CSS support or mirroring existing HTML pages. The choice is not simply PHP versus non-PHP: it is whether the rendering engine has the browser capabilities your document needs.

Choose an approach for your document

Approach JavaScript and CSS Deployment and useful fit
Headless Chrome with chrome-php/chrome Runs page JavaScript in a real browser engine and supports modern browser layout; you control when to print. Self-hosted. Requires a compatible Chrome or Chromium executable alongside PHP. A good fit when the document depends on scripts or modern CSS.
Hosted Chrome service Can render in a browser environment; available wait conditions and print controls depend on the service. External service rather than a locally operated browser. ChromeHeadless.io documents a PHP client that accepts an HTML string through export() and offers PDF print options and wait conditions.
Dompdf Does not execute JavaScript; mostly CSS 2.1-oriented. PHP library. Consider it for deterministic HTML/CSS documents when a browser runtime is not needed.
mPDF Accepts HTML strings, but is not a general browser JavaScript runtime. PHP library useful for controlled document layouts and features such as pagination, headers, footers, barcodes, and tables of contents.
wkhtmltopdf Uses Qt WebKit. Compatibility with a particular modern JavaScript application is not established universally; validate your page. Headless command-line executable that PHP can invoke or feed HTML to. Choose it only after testing the required scripts and assets.

The chrome-php/chrome documentation lists PHP 7.4–8.5 and Chrome/Chromium 65 or newer as requirements. Confirm the package version and browser binary available in your actual deployment before relying on those ranges. No universal speed, memory, or pixel-fidelity winner is established: results depend on document size, scripts, assets, fonts, browser version, and server limits.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Epson EcoTank ET-2800 Wireless Color All-in-One Supertank Printer - Black
  • 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

Render an HTML string with PHP and headless Chrome

1. Install the PHP client and browser

Install the chrome-php/chrome package with Composer and make a compatible Chrome or Chromium executable available to the PHP process. The executable must be runnable in the environment where the PHP job runs; a browser installed on your laptop is not automatically available to a web server, worker, or container.

composer require chrome-php/chrome

Depending on your environment, Chrome may also require sandbox or shared-memory configuration. Do not disable browser security controls indiscriminately just to make a deployment start; use the browser and operating-system configuration appropriate to your isolated runtime.

2. Assemble complete HTML, including scripts and resolvable assets

Use a complete document string, not just a fragment, when the layout relies on a document head, styles, or script loading order. The example below includes an inline script that inserts content and sets an explicit readiness marker. Replace the sample body and script with your own document. External stylesheets, images, fonts, and scripts need URLs resolvable from the browser’s rendering context; relative paths need a meaningful base URL or should be made absolute.

3. Wait for rendering, then print

This PHP example opens a page, loads the HTML string, waits for the page load event and the application-specific marker, and saves a PDF. It also waits for the browser font set and already-started images before printing. Adapt the readiness marker to your own app: a page-load event alone does not prove that later data fetching, timers, or client-side rendering has finished.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Epson EcoTank Photo ET-8550 Wireless Wide-Format All-in-One Tank Printer
  • 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⁴
<?php
require __DIR__ . '/vendor/autoload.php';

use HeadlessChromiumBrowserFactory;

$html = <<<'HTML'
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Rendered report</title>
  <style>
    body { font: 16px Arial, sans-serif; margin: 32px; }
    h1 { color: #174ea6; }
  </style>
</head>
<body>
  <h1>Monthly report</h1>
  <div id="report">Preparing report…</div>
  <script>
    // Replace with your real rendering work. Set this only when it is done.
    document.querySelector('#report').textContent = 'Report data is ready.';
    window.__PDF_READY__ = true;
  </script>
</body>
</html>
HTML;

$browser = (new BrowserFactory())->createBrowser();

try {
    $page = $browser->createPage();
    $page->setHtml($html);

    // Wait for document loading, the app's explicit ready signal,
    // fonts, and images that have already begun loading.
    $page->evaluate('new Promise(resolve => {
        const check = async () => {
            if (document.readyState !== "complete" || window.__PDF_READY__ !== true) return false;
            if (document.fonts && document.fonts.ready) await document.fonts.ready;
            await Promise.all(Array.from(document.images, image => {
                if (image.complete) return Promise.resolve();
                return new Promise(done => {
                    image.addEventListener("load", done, { once: true });
                    image.addEventListener("error", done, { once: true });
                });
            }));
            return true;
        };
        const poll = async () => {
            if (await check()) resolve(true);
            else setTimeout(poll, 50);
        };
        poll();
    })')->waitForResponse();

    $page->pdf([
        'printBackground' => true,
        'paperWidth' => 8.27,
        'paperHeight' => 11.7,
    ])->saveToFile(__DIR__ . '/report.pdf');
} finally {
    $browser->close();
}

The example uses A4-like paper dimensions in inches and prints backgrounds. Set those dimensions and print options to match the document you need. If you already have a page-specific promise or DOM marker for completion, wait for that instead of adding a fixed sleep. The image wait handles images already represented in the document; lazy images may require scrolling or another explicit loading step before printing. Fonts that fail to load can still leave the PDF with fallback typography.

Check the exact API signatures against the installed chrome-php/chrome version when upgrading the package. The library exposes browser-page control, JavaScript evaluation, and PDF creation, but method behavior and options are version-dependent. Keep the PHP request or background job alive until the print operation has completed, and close the browser in a finally block so failures do not leave Chromium processes running.

Make readiness and asset loading reliable

Use an application signal, not an arbitrary delay

A short sleep may work on a developer machine and fail under server load or when an API response is slow. Set a marker such as window.__PDF_READY__ = true only after the work that affects the output is complete. If the page fetches data, wait for the data and resulting DOM update. For a page you do not control, a documented network-idle condition can help, but long polling or analytics may prevent network idle indefinitely; an application-specific selector or state is usually more precise.

Resolve every resource from the renderer

A browser loading an HTML string has no automatic knowledge of the directory from which your PHP source came. Absolute asset URLs are simplest. If you use relative URLs, establish a base URL appropriate to the page and ensure the renderer can reach it. Hosted HTML-string rendering may expose a baseUrl or httpHost setting; use the provider’s documented configuration when relative links are necessary. Verify access to fonts, images, stylesheets, and scripts from the actual worker, not only from a browser on your workstation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
HP Smart Tank 5000 Wireless All-in-One Ink Tank Printer, Scanner, Copier with 2 Years of Ink Included, Best-for-Home, Cartridge-Free, Refillable and AI-Enabled. (5D1B6A)
  • 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.

Choose page layout intentionally

Use print CSS, page-break rules, paper dimensions, and margins for a multipage report. Inspect the PDF for clipped elements, unexpected blank pages, missing backgrounds, and content that crosses page boundaries. CSS that appears correct in a screen viewport may paginate differently in print mode. For a chart or other canvas, wait until its rendering code has finished before printing; the PDF captures the page state at print time.

Protect the renderer and the PHP service

Treat HTML as untrusted if any part comes from a user or external system. The mPDF manual specifically warns that mPDF is not meant to receive outside-user HTML/CSS without vetting and sanitization. Apply at least the same discipline to browser-based rendering: executing hostile scripts in a server-side browser creates a broader risk than laying out static markup.

  • Sanitize and validate input before rendering; do not assume ordinary browser sanitization is sufficient for your threat model.
  • Restrict outbound network access where possible, so supplied HTML cannot use the renderer to reach internal services.
  • Control local-file access and do not expose credentials, cookies, or sensitive files to page scripts.
  • Run rendering in an appropriately isolated process or container, with sensible time and resource limits.
  • Handle failures and temporary files deliberately, and avoid returning raw browser diagnostics or secrets to an untrusted caller.

Common failures and practical fixes

Symptom Likely cause What to check
JavaScript-generated content is missing The renderer does not execute JavaScript, or printing began before scripts finished. Use a browser engine; wait for the application’s completion signal before calling PDF.
PHP cannot start Chrome The executable is missing, not executable by the PHP user, incompatible, or blocked by the runtime environment. Check the browser installation and permissions from the same process/container that runs PHP; confirm PHP and Chrome versions meet the package requirements.
Images, fonts, or CSS are missing Relative URLs have no useful base, the browser cannot reach the asset host, or a request fails. Use resolvable URLs, check access from the renderer, and wait for required assets before printing.
PDF sometimes omits late content Rendering depends on asynchronous requests, timers, or slow assets that were not included in the wait condition. Wait for an explicit DOM marker or application promise; log readiness and asset failures in the rendering environment.
Layout differs from the browser preview Print pagination, paper size, margins, missing print backgrounds, or font substitution changes the result. Set paper and print options deliberately, add print CSS, and inspect the output under the same browser version used in production.
PDF generation hangs or consumes excessive resources A page may have endless polling, an unending wait condition, large assets, or expensive scripts. Set job-level limits, use a bounded readiness strategy, and test representative documents under deployment limits.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability, and cost trade-offs

Self-hosted Chrome gives you control over browser versions, page timing, and infrastructure, but you also operate the browser process and its isolation, updates, and resource limits. A hosted browser API removes some local browser operations but introduces an external service dependency and requires you to account for that service’s configuration and costs. PHP-only renderers can be simpler for static templates, but they cannot satisfy a requirement for browser JavaScript execution when the engine does not run scripts.

There is no sourced universal benchmark for startup latency, throughput, or memory across these choices. Measure with representative HTML, scripts, images, and fonts in the deployment environment. For reliability, record whether each stage succeeded—page creation, resource loading, readiness, and PDF writing—and make retries bounded so a permanently broken page does not consume a worker indefinitely.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
NDYIN Portable Printers Wireless for Travel, N80 Bluetooth Thermal Printer
  • 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

Or skip the browser setup

If what you need is a screenshot or PDF of a reachable website URL—not conversion of an arbitrary PHP HTML string—ScreenshotNeo offers a one-request API. Its URL-based API is a different input workflow from passing your in-memory HTML string to a browser. Use the local Chrome method above when the HTML string itself is the document to render.

The following cURL example saves a WebP screenshot of a URL. See the ScreenshotNeo API documentation for the available request and output options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
  • Cookie and consent banners are accepted before capture, and 60+ known consent platforms, newsletter popups, and chat widgets can be removed; each step can be turned off.
  • Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing; response headers identify the page verdict and whether the request was billed.
  • An MCP server gives AI agents tools to take screenshots, get page information, and capture PDFs.
  • The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots.

Sign up for 1,000 free screenshots a month, with no card required.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.