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

Guzzle fetches HTML; it does not render PDFs. Use Guzzle to retrieve the page, then pass its HTML to a PDF renderer such as Dompdf. For a page that depends on modern CSS or JavaScript, use a browser-based renderer instead.

How the conversion works

The workflow has two separate jobs: Guzzle makes an HTTP request and returns the response body; a renderer lays out that HTML and produces a PDF. For a straightforward PHP implementation, install Guzzle and Dompdf with Composer, fetch the page, and give the resulting string to Dompdf.

The example below returns the PDF as a download. It follows Dompdf’s documented sequence: load HTML, set paper, render, then stream or save the result. See the Guzzle documentation and Dompdf project documentation for their respective APIs.

Install the packages and render a page

Prerequisites

  • PHP must satisfy the requirements of the Guzzle and Dompdf versions you install. Guzzle’s stable documentation lists PHP 7.2.5 as a requirement; verify the requirement for the exact package release you pin.
  • Composer must be available in your project.
  • The PHP process needs network access to the target page. If the page is private, use appropriate authentication rather than exposing credentials in source code.

Install with Composer

composer require guzzlehttp/guzzle dompdf/dompdf

Fetch HTML and return a PDF

<?php

require __DIR__ . '/vendor/autoload.php';

use GuzzleHttpClient;
use DompdfDompdf;

$client = new Client([
    'timeout' => 20,
    'allow_redirects' => true,
]);

$response = $client->get('https://example.com/page');
$html = (string) $response->getBody();

$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream('page.pdf', ['Attachment' => true]);

Replace the example URL with the page you control or are authorized to retrieve. With the default Guzzle behavior, unsuccessful HTTP responses generally raise an exception; handle exceptions at the application boundary and log useful details without logging secrets or sensitive page contents.

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

Save the PDF to a server-side file

If the application needs a file rather than a download response, render the document and write the PDF bytes returned by output():

$dompdf->render();
$pdf = $dompdf->output();

if (file_put_contents(__DIR__ . '/page.pdf', $pdf) === false) {
    throw new RuntimeException('Could not save the PDF.');
}

Ensure the destination directory is writable by the PHP process and is not exposed as a public upload location unless that is intended. Dompdf documents both streaming and the output-then-save pattern in its project documentation.

Make retrieval more reliable

A successful HTTP request does not guarantee that the response is the page you expected. Validate status, type, size, and content before rendering. This avoids trying to create a PDF from an error page, an unexpectedly large response, or a non-HTML payload.

$response = $client->get('https://example.com/page');
$status = $response->getStatusCode();
$contentType = $response->getHeaderLine('Content-Type');
$body = (string) $response->getBody();

if ($status < 200 || $status >= 300) {
    throw new RuntimeException("Unexpected HTTP status: {$status}");
}
if (stripos($contentType, 'text/html') === false) {
    throw new RuntimeException("Expected HTML, received: {$contentType}");
}
if (strlen($body) > 5_000_000) {
    throw new RuntimeException('HTML response exceeds the configured size limit.');
}

$dompdf->loadHtml($body);

The five-megabyte check is an example application limit, not a Guzzle or Dompdf default. Choose a limit appropriate to your workload, memory budget, and trusted content. Also set an overall request timeout, and apply limits to the final rendered document and any external resources the renderer may fetch.

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

Read the response body once

Guzzle exposes a stream body. Casting it to a string, as in the main example, reads the stream into a PHP string. Alternatively, call $response->getBody()->getContents(). Do not assume a consumed stream can be read again from the beginning without rewinding it.

Choose a renderer for the page you have

The renderer determines how faithfully the source becomes a paginated document. There is no universally best engine: compare layout fidelity, JavaScript needs, deployment dependencies, fonts and images, page-break controls, and the security boundary around remote content.

Renderer When it fits Important trade-off
Dompdf A Composer-based PHP workflow with common HTML, tables, images, external stylesheets, and print rules. Its layout engine is mostly CSS 2.1 with selected CSS3 support; sophisticated modern layouts may not match a browser.
mPDF Generating PDFs from UTF-8 HTML in PHP, including use cases needing its custom HTML tags. The mPDF manual describes the project as dated and warns that externally supplied HTML/CSS must be vetted and sanitized.
wkhtmltox A separate converter based on QtWebKit for rendering HTML into PDF and image formats. It brings native/runtime deployment considerations beyond a Composer-only PHP library.
Headless Chrome Pages that need modern browser CSS support or close mirroring of an existing web page. It requires a browser-based runtime and its associated deployment and operational setup.

Dompdf describes itself as mostly CSS 2.1 compliant in its project documentation. The mPDF manual discusses its own scope and points to headless Chrome where modern CSS fidelity is important: mPDF manual. The PHP manual describes libwkhtmltox as an LGPLv3 library using QtWebKit: PHP wkhtmltox manual.

Control resources and untrusted HTML

Rendering HTML can involve loading images, stylesheets, fonts, or other resources. Treat that as a security boundary, not a harmless formatting detail. Dompdf’s documentation says remote access is disabled by default. If you enable remote images or stylesheets, make a deliberate decision about which origins may be accessed; do not let arbitrary input direct the renderer to arbitrary network or local-file resources.

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

mPDF explicitly warns against receiving outside users’ HTML/CSS without vetting and sanitization. When documents include user-controlled markup:

  • Sanitize or reject unsafe HTML and CSS before rendering; ordinary browser-level assumptions are not enough.
  • Keep remote resource access disabled unless the use case requires it. If enabled, restrict it to controlled, allowlisted origins.
  • Limit request duration, response size, rendering workload, and output size to protect memory and worker capacity.
  • Do not pass arbitrary file paths, credentials, or unrestricted URLs from user input into the fetch or rendering process.
  • Use a controlled environment for rendering documents from untrusted sources, and avoid logging full contents that may contain private data.

See Dompdf’s security and configuration guidance and the mPDF manual for the relevant renderer-specific controls.

Or skip the browser setup

If you need a screenshot rather than a paginated HTML-to-PDF workflow, ScreenshotNeo is a website screenshot API and MCP server for developers. A single GET request returns PNG, JPEG, WebP, or PDF. Its documented API options include full-page capture, CSS-selector element capture, viewport and device presets, PDF paper and page-range settings, custom CSS and JavaScript, wait conditions, and caching. See the ScreenshotNeo API documentation.

For a PDF response, request the PDF format with the API’s supported parameters; this minimal one-call example demonstrates the endpoint request pattern and saves its response body:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" 
  -d access_key=YOUR_API_KEY 
  --data-urlencode url=https://stripe.com 
  -o shot.webp

The example saves an image using the endpoint’s default response. Configure the PDF output options in the API request when the result must be a PDF. ScreenshotNeo accepts a URL and can return a PDF as well as image formats.

  • Cookie/consent banners are accepted before capture, and 60+ known consent platforms, newsletter popups, and chat widgets can be removed; each cleanup step can be turned off.
  • Bot checks/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 provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients.
  • The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Every feature is on every plan.

Sign up for ScreenshotNeo’s free plan for 1,000 screenshots a month with no card.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot common failures

Guzzle times out or cannot connect

Check that the PHP runtime has network access, the host resolves, TLS certificates are configured, and the destination is reachable from the server—not just from your laptop. Increase the timeout only when the target legitimately needs longer; do not remove time limits for untrusted or unpredictable URLs.

The PDF contains an error page or non-HTML content

Inspect the HTTP status and Content-Type before calling loadHtml(). A redirect may land on a login or error page, or the server may return JSON or a PDF instead of HTML. Confirm the final response is the intended HTML document.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

Images, stylesheets, or fonts are missing

Check whether resources use absolute URLs and whether the renderer is permitted to fetch them. Dompdf remote access is disabled by default; enable only the specific remote behavior needed and restrict resource origins. Relative links may also resolve differently than they did in the original website, so use a controlled base URL or rewrite resource paths as appropriate.

The layout differs from the browser

Dompdf is not a full modern browser engine. If the page depends on advanced CSS, browser JavaScript, or dynamic application state, a PHP HTML renderer may not reproduce it. Simplify the print HTML and CSS, or choose a browser-based renderer such as headless Chrome when fidelity is the priority.

Memory use or rendering time grows unexpectedly

Large pages, many high-resolution images, external fonts, and long documents can use substantial memory and time. Limit response and output sizes, constrain remote resources, and render in a worker with appropriate resource limits. Avoid fetching arbitrary page URLs in an endpoint open to unauthenticated users.

Version and deployment notes

The Dompdf project’s 2026 search snapshot listed version 3.1.5; treat that as time-sensitive, not a claim about the version Composer will install today. Check the package version in your lock file and consult current project requirements before deployment. Likewise, confirm the PHP version requirement for the exact Guzzle release rather than relying on a general documentation figure.

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.

Frequently Asked Questions

Does Guzzle convert HTML to PDF by itself?

No. Guzzle retrieves HTTP responses; a separate renderer such as Dompdf creates the PDF.

Can Dompdf run JavaScript from the page?

Dompdf is an HTML/CSS renderer, not a browser engine for executing page JavaScript. Use a browser-based renderer when the page must run scripts to produce its final state.

Should I enable remote resources in Dompdf?

Only when required for the document, and with restrictions on the origins the renderer can access.

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.