Use a real headless Chrome or Chromium browser when your PHP code must turn HTML and CSS into an image. A browser handles modern CSS, web fonts, JavaScript, lazy-loaded images, and responsive layouts. In PHP, the most practical routes are Spatie Browsershot (PHP controlling Puppeteer), the chrome-php/chrome library (PHP controlling Chrome directly), or a hosted rendering API when you do not want to install and operate a browser.
This guide shows runnable local PHP examples, explains when a hosted service is safer operationally, separates raster images from PDF workflows, and covers sizing, assets, security, reliability, and common failures.
Choose the rendering path first
The correct implementation depends on what “HTML to image” means for your project.
| Path | Rendering location | Best fit | Main trade-off |
|---|---|---|---|
| Spatie Browsershot | Local Chrome/Chromium through Puppeteer | Applications already using Node tooling or needing full browser behavior | PHP, Node.js, Puppeteer, and a compatible browser must be deployed together |
| chrome-php/chrome | Local Chrome/Chromium controlled directly from PHP | PHP-first services that need viewport, clipping, JavaScript, and image output | Chrome/Chromium remains a system dependency; verify compatibility with your runtime |
| Hosted HTML/CSS rendering API | Vendor-managed Google Chrome | Teams that prefer an HTTP request over browser operations | Credentials, network dependency, vendor limits, and sending HTML/assets outside your infrastructure |
| Dompdf or mPDF | PHP PDF renderer | PDF documents, not browser screenshots | Do not expect a direct PNG/JPEG/WebP screenshot equivalent |
For a screenshot of a JavaScript-heavy page, a local or hosted Chromium renderer is the dependable choice. For a static document whose required output is PDF, use a PDF library instead of forcing a raster workflow.
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Option 1: PHP with Spatie Browsershot
Browsershot controls headless Google Chrome through Puppeteer. Its documented workflow can render a URL, an HTML string, or a local HTML file and save an image or PDF. Installation therefore includes PHP packages plus Node.js, Puppeteer, and a browser binary.
Install and verify prerequisites
- Install the Browsershot Composer package in your application.
- Install Node.js and Puppeteer as required by the Browsershot version you selected.
- Make sure the PHP worker user can execute Node and Chrome and can write to the destination directory.
- Run a small capture from the same service account used in production; a browser that works in your shell may fail under PHP-FPM because of PATH, permissions, or sandbox settings.
Render a URL to WebP
<?php
require __DIR__ . '/vendor/autoload.php';
use SpatieBrowsershotBrowsershot;
Browsershot::url('https://example.com')
->windowSize(1200, 800)
->deviceScaleFactor(2)
->waitUntilNetworkIdle()
->save('storage/app/example.webp');
The destination extension determines the image format in common Browsershot usage. Use a writable absolute path in workers and containers, and create the directory before capture.
Render an HTML string
<?php
require __DIR__ . '/vendor/autoload.php';
use SpatieBrowsershotBrowsershot;
$html = '<!doctype html>
<html><head>
<meta charset="utf-8">
<style>
body { margin: 0; font-family: Arial, sans-serif; }
.card { width: 1200px; padding: 64px; background: #111827; color: white; }
</style>
</head><body>
<section class="card"><h1>Release 2.4</h1><p>Generated by PHP</p></section>
</body></html>';
Browsershot::html($html)
->windowSize(1328, 800)
->setScreenshotType('webp')
->save('storage/app/release-card.webp');
For external fonts, images, or stylesheets, use absolute HTTPS URLs or a correctly configured base URL. A relative path that works in a browser tab may not resolve when the HTML is supplied directly as a string.
Capture only one element
Give the target an unambiguous CSS selector and use Browsershot’s selector/clipping capability. This avoids producing a full-page image when the required asset is a card, chart, or invoice panel. Keep the element’s width deterministic; auto-sized content can produce different dimensions as text or fonts load.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Option 2: Control Chrome directly with chrome-php/chrome
The chrome-php/chrome library exposes page navigation, HTML assignment, JavaScript evaluation, viewport control, and screenshots from PHP. Its repository lists PHP 7.4–8.5 and Chrome/Chromium 65 or newer as requirements; confirm those ranges against the current package release before pinning versions.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Minimal URL screenshot
<?php
require __DIR__ . '/vendor/autoload.php';
use HeadlessChromiumBrowserFactory;
$factory = new BrowserFactory();
$browser = $factory->createBrowser([
'headless' => true,
'noSandbox' => true, // only when your container policy requires it
]);
try {
$page = $browser->createPage();
$page->setViewport(1200, 800)->await();
$page->navigate('https://example.com')->waitForNavigation();
$page->screenshot()->saveToFile(__DIR__ . '/example.png');
} finally {
$browser->close();
}
Use noSandbox only after assessing the container boundary; disabling Chrome’s sandbox reduces isolation. Prefer a correctly configured sandbox for production where possible.
Render supplied markup and clip an element
<?php
require __DIR__ . '/vendor/autoload.php';
use HeadlessChromiumBrowserFactory;
$html = '<html><body><div id="ticket" style="width:900px;padding:40px;background:white">Ticket</div></body></html>';
$browser = (new BrowserFactory())->createBrowser(['headless' => true]);
try {
$page = $browser->createPage();
$page->setHtml($html)->await();
$page->evaluate('document.fonts.ready')->await();
$page->screenshot()->setClip(0, 0, 980, 180)->saveToFile(__DIR__ . '/ticket.webp');
} finally {
$browser->close();
}
For a selector-specific crop, evaluate the element’s bounding rectangle, then pass those coordinates to the screenshot clip. Add a small wait after asynchronous application rendering so the rectangle is measured after layout stabilizes.
Make the capture deterministic
Set viewport and pixel density
CSS pixels and output pixels are different when device scale is greater than one. Fix the viewport for reproducible social cards and thumbnails, then choose a scale factor for sharper output. A 1200×630 CSS viewport at scale 2 produces a 2400×1260 raster image.
Wait for the page you actually need
- Wait for network idle when the page loads data and images over HTTP.
- Wait for a specific selector when an application has a clear “ready” element.
- Use an explicit delay only for unavoidable animations or third-party widgets.
- Disable transitions and animations with injected CSS when visual stability matters.
Handle images, fonts, and lazy loading
Full-page captures must scroll or otherwise trigger lazy images before the screenshot. Ensure image URLs are reachable from the browser process, and wait for document.fonts.ready before measuring text. If a font is blocked by CORS or an expiring signed URL, the browser may silently fall back to a different font and change line breaks.
Use print CSS only for print-like layouts
A screenshot uses screen media by default. If your stylesheet changes under @media print, explicitly choose the media mode supported by your library. Do not assume a PDF renderer’s pagination rules will match a raster screenshot.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Hosted API alternative
A hosted service accepts HTML/CSS or a URL over HTTP, runs the browser remotely, and returns an image URL or binary response. This removes Chrome maintenance from your PHP deployment, but you must review data handling, authentication, retention, request limits, and regional requirements before sending private markup, images, or fonts.
When this is the better operational choice
- Your PHP workers are serverless or otherwise cannot package Chromium.
- You need burst capacity without maintaining a browser pool.
- You want one API contract for screenshots from several languages.
- Your team prefers vendor-managed browser updates and patching.
Or skip the browser setup: ScreenshotNeo
ScreenshotNeo is a website screenshot API and MCP server. It accepts a URL and returns PNG, JPEG, WebP, or PDF. Before capture it accepts cookie/consent banners 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 are not billed, and response headers report the page verdict and billing status.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
One PHP request
<?php
$url = 'https://stripe.com';
$query = http_build_query([
'access_key' => 'YOUR_API_KEY',
'url' => $url,
]);
$ch = curl_init("https://api.screenshotneo.com/v1/shot?$query");
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 90,
]);
$bytes = curl_exec($ch);
if ($bytes === false) {
throw new RuntimeException(curl_error($ch));
}
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status >= 400) {
throw new RuntimeException("Screenshot request failed with HTTP $status");
}
file_put_contents(__DIR__ . '/shot.webp', $bytes);
See the ScreenshotNeo API documentation for the full option set, including full-page capture with lazy images loaded, CSS-selector element capture, dark mode, 12 device presets and custom viewports, retina scale, PDF paper settings and page ranges, custom CSS and JavaScript, click-before-capture, hidden selectors, waits, request/resource blocking, headers, cookies, user agent, Authorization, timezone, geolocation, transparent backgrounds, resizing, configurable-TTL caching, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, usage reporting, and the OpenAPI specification. Its parameter names are compatible with those used by other screenshot APIs, which can simplify migration.
Other language clients
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
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)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
Security and privacy boundaries
Sanitize untrusted HTML
Never pass user-supplied HTML straight into a privileged browser or PDF renderer. Remove scripts and dangerous URLs according to your application’s threat model, isolate the browser user, restrict outbound access where practical, and write output to a non-executable directory. mPDF’s documentation specifically warns that externally supplied HTML/CSS needs vetting beyond ordinary browser-level sanitization.
Protect credentials and internal pages
Keep API keys in environment variables, not templates or query strings visible in logs. If capturing an authenticated local page, use short-lived cookies or headers and ensure screenshots cannot expose secrets. A hosted API adds a data-transfer boundary; confirm that your privacy, residency, and retention requirements permit sending the content.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Performance, reliability, and cost
- Reuse browser processes carefully: launching Chrome for every request is slow; a controlled worker or browser pool reduces startup cost, but enforce page and memory limits.
- Bound every wait: network-idle waits can hang on analytics or streaming connections. Set a total timeout and a fallback selector/delay.
- Control concurrency: too many parallel pages can exhaust CPU and memory, causing blank captures or crashes.
- Cache stable outputs: hash the URL and relevant HTML/CSS inputs, and invalidate when assets change.
- Measure the result: record render duration, HTTP status, output dimensions, and browser errors. For hosted calls, retain the service’s response status and billing indicators.
- Budget honestly: local rendering costs infrastructure and maintenance; hosted pricing, concurrency, size, and retention vary and should be confirmed with the vendor before commitment.
Troubleshooting checklist
“Chrome executable not found” or process launch failure
Install Chrome/Chromium in the runtime image, expose its path to the library, and verify that the PHP worker’s PATH differs from your interactive shell. Confirm executable permissions.
Blank or partially rendered image
Wait for a ready selector or network idle, await fonts, and verify that image URLs are reachable from the server. For lazy content, trigger scrolling or use a full-page mode that loads lazy images.
Timeouts on otherwise valid pages
Third-party analytics, websockets, and ads can prevent network idle. Replace an unbounded idle wait with a selector wait plus a hard timeout, and block nonessential requests where your library supports it.
Different dimensions or text wrapping
Fix viewport, device scale, font loading, timezone, and locale. A missing web font or a different responsive breakpoint changes line breaks and element coordinates.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minute403, CAPTCHA, or login wall
Respect the site’s access controls. Supply authorized headers/cookies only when you have permission. A screenshot service cannot legitimately bypass a CAPTCHA; treat the result as a failed capture and do not bill or retry indefinitely.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
PDF output does not match the screenshot
PDF libraries implement document layout, often around CSS 2.1 and selected CSS3 features, rather than a full browser. Use Chromium for browser-faithful raster output and reserve Dompdf or mPDF for PDF deliverables.
Decision guide
- Choose Browsershot when your team is comfortable deploying Node, Puppeteer, and Chrome alongside PHP.
- Choose chrome-php/chrome when you want direct PHP control and can operate a compatible browser runtime.
- Choose a hosted API when browser operations, scaling, or serverless packaging outweigh data-transfer concerns.
- Choose Dompdf or mPDF only when the required artifact is a PDF, not a screenshot.
- Try ScreenshotNeo first when you want a hosted screenshot API with clean shots, billing only for successful captures, an MCP server for AI agents, and a $5 paid entry plan.
Frequently Asked Questions
Can PHP convert HTML to a PNG without JavaScript?
Yes. A headless Chrome workflow can render static HTML and CSS and save a PNG; JavaScript is only needed for client-rendered or interactive content.
Why does my screenshot have a white background?
The page may not set a background color, or the capture mode may not support transparency. Set the desired background in CSS or use a renderer option that explicitly enables a transparent background.
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 & 11Outdated 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 matchShould I save screenshots in the database?
Usually store the image in object storage or a filesystem and keep its path, dimensions, hash, and creation metadata in the database. Store binaries in the database only when your storage and backup design specifically requires it.
Is a PDF library interchangeable with a screenshot library?
No. Dompdf and mPDF target PDF layout. Browser screenshot libraries target the pixels produced by Chrome or Chromium, so CSS and JavaScript behavior can differ substantially.
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.

