October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
CSS

How to Load CSS from a URL for HTML-to-PDF in PHP with Dompdf

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

Yes. Dompdf can load a stylesheet from an HTTP or HTTPS URL when you enable isRemoteEnabled and the PHP runtime can fetch remote files through cURL or allow_url_fopen. The PDF server must also be able to reach the stylesheet and every font, image, or imported stylesheet that it references. Fetching the file successfully does not guarantee that Dompdf supports all of the CSS inside it: Dompdf documents a mostly CSS 2.1 renderer, with flexbox and CSS Grid unsupported.

This guide shows a complete implementation, the checks that prevent the most common failures, security controls for user-supplied HTML, and the separate user-stylesheet option exposed by the PHP wkhtmltox extension.

Minimal Dompdf implementation

Install Dompdf with Composer, create a fresh renderer for each document, enable remote resources, and put an ordinary <link> element in the HTML passed to loadHtml().

<?php
require 'vendor/autoload.php';

use DompdfDompdf;
use DompdfOptions;

$options = new Options();
$options->set('isRemoteEnabled', true);

$dompdf = new Dompdf($options);
$dompdf->loadHtml(<<<'HTML'
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="https://example.com/pdf.css">
</head>
<body>
    <h1>PDF heading</h1>
    <p>This text is styled by the remote stylesheet.</p>
</body>
</html>
HTML);
$dompdf->render();
$dompdf->stream('document.pdf');

The example.com address is illustrative; replace it with a stylesheet that the PDF-generating host can access. Dompdf’s upstream README is the authority for requirements that vary by installed release.

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.

What must be true for remote CSS to work

Remote access is enabled

isRemoteEnabled is separate from CSS parsing. Without it, Dompdf will not retrieve an HTTP, HTTPS, or other web resource even when the URL is valid.

PHP can make outbound requests

Dompdf’s documentation requires either cURL or PHP’s allow_url_fopen capability for remote resources. Check the PHP configuration used by the web worker or queue process, not only the CLI configuration. The PHP manual explains the behavior of URL wrappers in its Using remote files documentation.

A quick diagnostic script can show the active setting:

<?php
var_dump(extension_loaded('curl'));
var_dump(ini_get('allow_url_fopen'));

At least one supported retrieval path must be available, and outbound DNS, firewall, proxy, and TLS rules must permit the destination.

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

The response is really CSS

Open the stylesheet from the same server or container that runs PHP. Confirm that the response is a successful CSS document rather than a login page, an HTML error, a redirect to an internal hostname, or a bot-check page. Authentication that works in your browser may not work for a server-side request. Also check URLs in @import, url(), and font declarations: those are additional remote requests.

The renderer supports the CSS you use

A successful download only proves that bytes arrived. Dompdf describes itself as mostly CSS 2.1 compliant with some CSS3 support. Its README specifically says flexbox and CSS Grid are unsupported. A browser preview can therefore look correct while the PDF ignores layout rules. Table cells also cannot be split across pages, so a row must fit on one page.

Use a predictable stylesheet URL

Serve a dedicated print stylesheet instead of sending your entire application bundle. Keep URLs absolute when the document can be rendered from a worker with no meaningful base URL.

<link rel="stylesheet" href="https://static.example.org/pdf/print.css">

If the CSS imports other files, make those references reachable from the renderer:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
@import url("https://static.example.org/pdf/typography.css");
.invoice-logo { background-image: url("https://static.example.org/pdf/logo.png"); }

For repeatable output, pin the stylesheet to a versioned path or deploy CSS and HTML together. Avoid depending on a development server, session cookies, or a stylesheet that changes without a corresponding document release.

Build the document in a fresh Dompdf instance

Create one Dompdf object per HTML document. The upstream README warns that reusing an instance can carry parsing and rendering artifacts into later output. In a long-running worker, instantiate, render, stream or save, and then discard it for every job.

function renderPdf(string $html): string
{
    $options = new DompdfOptions();
    $options->set('isRemoteEnabled', true);

    $dompdf = new DompdfDompdf($options);
    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();

    return $dompdf->output();
}

$pdf = renderPdf('<link rel="stylesheet" href="https://example.com/pdf.css"><p>Invoice</p>');
file_put_contents(__DIR__ . '/invoice.pdf', $pdf);

Set paper size and orientation explicitly when those values matter to pagination. The remote stylesheet controls styling, but it does not change Dompdf’s implementation limits.

Security: remote access is a boundary

Enabling remote fetching means the renderer can make outbound requests. If an untrusted user can influence HTML or CSS, do not allow arbitrary URLs to become a server-side fetch facility.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Allowlist stylesheet, image, and font hostnames, or fetch assets yourself and provide validated local files.
  • Reject unexpected schemes and destinations, including internal network addresses, before rendering.
  • Sanitize user HTML and CSS; do not treat a browser-origin policy as protection for a server-side renderer.
  • Use a controlled egress network and ordinary request timeouts at the infrastructure layer.
  • Keep credentials out of public stylesheet URLs. If a resource requires authentication, retrieve and validate it in application code rather than exposing a reusable secret in HTML.

The Dompdf project documents remote access as security-sensitive. Your exact allowlist and network policy should match the data handled by your application.

Diagnose a missing or ineffective stylesheet

The PDF has default fonts and spacing

First verify isRemoteEnabled. Then request the URL from the PDF host with an HTTP client and inspect the status, redirects, content type, and body. A 200 response containing a sign-in page is still a failed CSS load. Check DNS and outbound firewall rules from the runtime environment.

Some rules apply, others do not

Inspect unsupported features before changing the URL. Replace flexbox or grid with simpler block layout, floats, or table-based structures where appropriate for this renderer. Check whether a selector, media query, pseudo-element, or CSS3 property is outside Dompdf’s supported set.

Images, fonts, or imports are absent

Each referenced asset needs its own reachable URL. Confirm that the asset host accepts requests from the PDF server, that redirects remain accessible, and that the response is the expected binary or CSS content. A stylesheet can load while one of its dependencies fails.

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

Styles worked once and then changed

Check deployment consistency and caching at your web server or CDN. Use versioned filenames or query-free release paths when deterministic documents are required. In queue workers, also verify that every job creates a new Dompdf instance.

The process is slow or times out

Reduce the number and size of remote dependencies, serve a small print stylesheet, and remove assets that are not needed in the PDF. A document with many external images, fonts, and imports has more network operations and more failure points than one with a compact asset set. Measure from the actual worker environment rather than from a desktop browser.

Rendering and layout limitations to plan for

Dompdf is not a browser engine. Design the PDF HTML around the renderer’s documented support rather than trying to reproduce an arbitrary modern web application.

  • Use normal document flow and explicit widths for important columns.
  • Test page breaks with realistic text lengths, not only short sample data.
  • Keep table rows small enough to fit on one page because table cells are not pageable.
  • Provide fallbacks for flexbox and grid layouts.
  • Test fonts and image dimensions at the target paper size and orientation.

The project README describes the latest stable code and may not match every release tag. Check the documentation and changelog for the version installed by your lockfile when behavior is version-sensitive.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Alternative: wkhtmltox user stylesheet

The PHP wkhtmltox extension exposes a renderer-level option named web.userStyleSheet. Its documented value is a URL or filesystem path to a user stylesheet, which is different from placing a <link> in the input HTML. The PHP manual documents the constructor option at wkhtmltoxPDFObject::__construct.

Choose this route only when your target environment already supports the extension and its installation constraints. The available documentation here does not establish comparative rendering quality, maintenance status, or suitability for every PHP version, so verify those details for your deployment. In either renderer, test the CSS features your document actually uses and control remote destinations.

Or skip the browser setup

If your actual need is a clean image or PDF capture of a web page rather than generating a PDF from your own PHP HTML, ScreenshotNeo provides a single HTTP request. Before capture it accepts the cookie or consent banner as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status.

cURL:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
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}`);

See the ScreenshotNeo documentation for output formats and options. ScreenshotNeo also has 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 screenshots each month with no card; paid plans start at $5 for 3,000 shots. Sign up for the free plan.

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.

Operational checklist

  1. Confirm the installed Dompdf version and read its matching documentation.
  2. Enable isRemoteEnabled in an Options object.
  3. Verify cURL or allow_url_fopen in the runtime that generates PDFs.
  4. Fetch the stylesheet URL from that same runtime and inspect its actual response.
  5. Check every imported stylesheet, font, and image URL.
  6. Replace unsupported flexbox and grid rules with renderer-compatible layout.
  7. Restrict untrusted remote URLs and outbound network access.
  8. Render each document with a fresh Dompdf instance and test pagination.

Frequently Asked Questions

Can I use a relative stylesheet URL with Dompdf?

Use an absolute URL when rendering in a worker or separate server. It removes ambiguity about the document base path and makes connectivity testing straightforward.

Does enabling remote access make Dompdf a full browser?

No. Remote access controls retrieval; Dompdf still has its own CSS implementation limits, including the documented lack of flexbox and CSS Grid support.

Should I reuse one Dompdf object in a queue worker?

No. Create a new instance for each HTML document, as the upstream project warns that reused instances can retain rendering artifacts.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Read next

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.