How to Convert HTML to PDF with PDFCrowd in PHP
Install PDFCrowd’s PHP client, convert a URL, HTML string, or file, configure the PDF, and return or store it with reliable error handling.
Use PDFCrowd’s official PHP client when you need to turn a reachable web page, an HTML string, or an HTML file into a PDF. Install it with Composer, create an HtmlToPdfClient using your PDFCrowd credentials, choose the conversion method that matches your input, and either save the result to a file or return its PDF bytes. The examples below use placeholders; configure your own credentials as secrets.
PDFCrowd’s client guide documents the install command, conversion methods, options, and Pdfcrowd\Error exception. See the official PHP guide and PHP examples.
1. Install the PHP client and configure credentials
From your project directory, install the client:
composer require pdfcrowd/pdfcrowd
Load Composer’s autoloader and create the client. Keep the username and API key in environment variables or your application’s secret manager; do not commit live credentials to source control.
<?php
require __DIR__ . '/vendor/autoload.php';
$username = getenv('PDFCROWD_USERNAME');
$apiKey = getenv('PDFCROWD_API_KEY');
if (!$username || !$apiKey) {
throw new RuntimeException('PDFCrowd credentials are not configured.');
}
$client = new \Pdfcrowd\HtmlToPdfClient($username, $apiKey);
The official examples also show demo credentials for trying the integration. Use your own account credentials for production conversions.
2. Choose the input method
There are three common inputs: a URL, an HTML string, or a local HTML file or archive. Each has a method that writes to a path and a method that returns PDF bytes.
| Input | Save to a path | Return PDF bytes | Use when |
|---|---|---|---|
| Web page URL | convertUrlToFile($url, $path) |
convertUrl($url) |
The page is publicly reachable by PDFCrowd’s servers. |
| HTML string | convertStringToFile($html, $path) |
convertString($html) |
Your PHP application has rendered or assembled the HTML. |
| HTML file or archive | convertFileToFile($input, $path) |
Use the corresponding in-memory file conversion method | The markup and possibly its local resources live in files. |
URL conversion is convenient, but the URL must be reachable from PDFCrowd’s servers. Passing HTML directly gives your application control over the content, but referenced CSS, images, fonts, and scripts still need to be reachable or included with the input. For relative asset paths, provide a suitable <base href="…"> or use absolute URLs.
Convert a web page URL
<?php
require __DIR__ . '/vendor/autoload.php';
$client = new \Pdfcrowd\HtmlToPdfClient(
getenv('PDFCROWD_USERNAME'),
getenv('PDFCROWD_API_KEY')
);
$url = 'https://example.com/invoice/123';
$outputPath = __DIR__ . '/invoice-123.pdf';
try {
$client->convertUrlToFile($url, $outputPath);
if (!is_file($outputPath) || filesize($outputPath) === 0) {
throw new RuntimeException('The PDF output file is missing or empty.');
}
} catch (\Pdfcrowd\Error $e) {
error_log('PDFCrowd conversion failed: ' . $e->getMessage());
http_response_code(502);
exit('Could not generate the PDF.');
}
To hold the PDF in memory instead, use convertUrl($url); it returns the PDF as a PHP string.
Convert an HTML string
<?php
require __DIR__ . '/vendor/autoload.php';
$client = new \Pdfcrowd\HtmlToPdfClient(
getenv('PDFCROWD_USERNAME'),
getenv('PDFCROWD_API_KEY')
);
$html = '<!doctype html>
<html>
<head>
<meta charset="utf-8">
<base href="https://example.com/">
<style>body { font-family: sans-serif; }</style>
</head>
<body><h1>Invoice 123</h1><p>Amount due: $42.00</p></body>
</html>';
$outputPath = __DIR__ . '/invoice-123.pdf';
$client->convertStringToFile($html, $outputPath);
// Or keep the PDF bytes in memory:
// $pdfBytes = $client->convertString($html);
For content generated from user input, escape or sanitize values according to your application’s HTML security rules before constructing the document.
Convert a local HTML file or archive
<?php
require __DIR__ . '/vendor/autoload.php';
$client = new \Pdfcrowd\HtmlToPdfClient(
getenv('PDFCROWD_USERNAME'),
getenv('PDFCROWD_API_KEY')
);
$inputPath = __DIR__ . '/reports/monthly-report.html';
$outputPath = __DIR__ . '/monthly-report.pdf';
$client->convertFileToFile($inputPath, $outputPath);
If the HTML references local images, stylesheets, or scripts, those resources must be reachable or supplied with the input. PDFCrowd documents supported ZIP or tar archives for bundling the HTML and its resources while preserving relative paths. For an archive containing more than one HTML file, configure the documented option that selects the main HTML file.
3. Configure page layout and rendering
Set client options before calling a conversion method. The PHP guide documents controls for page size, margins, orientation, headers and footers, content viewport width, scale, print media, custom CSS, custom JavaScript and readiness, and converting a selected element. Consult the PHP client guide and examples for the exact option names and accepted values for the installed client version.
For example, the guide uses a balanced viewport setting. Treat that as an explicit configuration choice, not an assumed default. Configure only the options that matter to your document so the settings remain easy to review.
// Illustrative: use the exact option names and values documented
// for your installed PDFCrowd PHP client version.
$client->setPageSize('A4');
$client->setPageOrientation('portrait');
$client->setContentViewportWidth('balanced');
$client->setPrintMedia(true);
$client->setCustomCss('body { color: #222; }');
$client->convertUrlToFile('https://example.com/report', __DIR__ . '/report.pdf');
Option method names and accepted values can vary with client/API versions; verify them against the official guide rather than copying an option blindly. The research source confirms the available categories of controls, not every signature.
4. Return a downloadable PDF from PHP
For a web download, use a POST action for the conversion, generate the PDF bytes, then send them with Content-Type: application/pdf. Generate the entire PDF before sending headers so a conversion error cannot leave the response looking like a partial PDF.
<?php
require __DIR__ . '/vendor/autoload.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
header('Allow: POST');
exit('Use POST to request the PDF.');
}
$client = new \Pdfcrowd\HtmlToPdfClient(
getenv('PDFCROWD_USERNAME'),
getenv('PDFCROWD_API_KEY')
);
$html = '<!doctype html><html><body><h1>Generated report</h1></body></html>';
try {
$pdfBytes = $client->convertString($html);
} catch (\Pdfcrowd\Error $e) {
error_log('PDFCrowd conversion failed: ' . $e->getMessage());
http_response_code(502);
exit('The PDF could not be generated.');
}
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="report.pdf"');
header('Content-Length: ' . strlen($pdfBytes));
echo $pdfBytes;
exit;
Choose a safe, application-controlled filename. Do not insert untrusted text directly into a response header.
5. Handle errors and store output safely
The PHP client throws Pdfcrowd\Error for conversion or validation failures. Catch it at the conversion boundary, log diagnostic details on the server, and return an appropriate HTTP status and a generic message to the user. Avoid exposing API keys or sensitive source HTML in error responses.
When using a file output method, verify the file was created and is non-empty if later code depends on it. When writing returned bytes yourself, check the result of file_put_contents:
try {
$pdfBytes = $client->convertString($html);
$written = file_put_contents(__DIR__ . '/report.pdf', $pdfBytes, LOCK_EX);
if ($written === false || $written !== strlen($pdfBytes)) {
throw new RuntimeException('Could not write the complete PDF.');
}
} catch (\Pdfcrowd\Error $e) {
error_log('PDFCrowd conversion failed: ' . $e->getMessage());
http_response_code(502);
exit('The PDF could not be generated.');
}
For sensitive documents, store files outside the public web root and serve them through an authorized download route. Clean up temporary files after use and avoid reusing predictable paths across concurrent requests.
6. Use the HTTP API directly when needed
The PHP client is the simplest path for a PHP application. If you need to call the service without that client, PDFCrowd’s HTTP guide documents a POST request to https://api.pdfcrowd.com/convert/24.04/, HTTP Basic authentication using the account username and API key, form fields, and PDF bytes in a successful response. Uploads use multipart form data.
The version shown here is the endpoint version documented in the research source; it is not a claim that this is the latest version. Keep the version explicit and check the current official documentation before changing it. See the HTTP API guide.
curl --user "$PDFCROWD_USERNAME:$PDFCROWD_API_KEY" \
--form-string "url=https://example.com/report" \
"https://api.pdfcrowd.com/convert/24.04/" \
--output report.pdf
For API calls from PHP, the official client handles request construction and response processing. Prefer it unless you specifically need to manage the HTTP request yourself.
7. Troubleshooting common problems
| Symptom | Likely cause | What to check |
|---|---|---|
| Authentication or validation exception | Missing, incorrect, or mismatched username/API key, or an invalid option. | Check the configured secret values and the option names/values against the installed client’s documentation. Catch Pdfcrowd\Error. |
| A URL conversion cannot load the page | The source URL is not reachable from PDFCrowd’s servers. | Check that the URL is accessible to the conversion service and does not depend on a local-only hostname or network. |
| Images or styles are missing | Referenced assets cannot be reached, or relative URLs resolve against the wrong location. | Use absolute asset URLs, set a suitable <base href>, or bundle local resources in a supported archive. |
| Wrong HTML file is converted from an archive | The archive contains multiple HTML files and no main file was selected. | Set the documented archive option for the intended entry HTML file. |
| Layout differs from the browser | Viewport, page size, print media, scale, readiness, or custom rendering settings differ. | Set the viewport and page options explicitly; use the documented custom CSS/JavaScript and readiness controls where needed. |
| Download is empty or corrupted | Output was sent before conversion completed, a failure was swallowed, or a file write was incomplete. | Generate bytes first, catch conversion errors, set the PDF content type only after success, and check write results. |
| PHP memory pressure on large output | The complete PDF is being held in a PHP string. | Use the client’s file-output method when you do not need the bytes in memory; avoid unnecessary duplicate copies. |
8. Performance, reliability, and cost considerations
The reviewed documentation does not provide a benchmark or numerical performance guarantee, so plan around the work your own documents require. Large pages, remote assets, and custom rendering can add work. Keep the source HTML and assets focused, avoid repeated conversions when the source has not changed, and measure representative documents in your deployment environment.
For reliability, make source URLs and assets stable and reachable, handle Pdfcrowd\Error, and avoid sending a download response until conversion succeeds. If a conversion is part of a user-facing request, decide how your application reports a failed generation and whether it should offer a retry. When storing output, use unique or safely managed paths and verify writes.
Conversion is a hosted API operation, so review the current PDFCrowd account pricing and limits before production use; the cited implementation documentation does not establish current prices or quotas. Keep the package and API version details aligned with current official documentation. The research source documents HTTP endpoint version 24.04 but does not establish it as the newest.
9. Or skip the browser setup
If your actual output is a screenshot or a PDF capture of a rendered web page, ScreenshotNeo offers a website screenshot API and MCP server. PDFCrowd remains the direct tutorial path for converting HTML content to PDF; ScreenshotNeo is an alternative when you want a rendered-page capture without managing browser infrastructure.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo docs for API options. The same endpoint can return a PDF by configuring the documented output format.
ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed. Its MCP server lets AI agents use screenshot tools, and 1,000 screenshots a month are free without a card; paid plans start at $5 for 3,000 shots.
Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.
Frequently asked questions
Can I convert HTML generated by my PHP application without publishing it?
Yes. Pass the HTML string to convertString or convertStringToFile. Make sure any referenced assets are reachable or included with the input.
Should I return bytes or save directly to a file?
Return bytes when the application needs to stream a download or process the PDF in memory. Use file output when you want a stored artifact and want to avoid holding the full PDF string in memory.
Can PDFCrowd convert an HTML bundle with local assets?
Yes. The documentation describes packaging local HTML and its assets in a supported ZIP or tar archive, with relative paths preserved. Select the main HTML file if the archive contains several.
Is the HTTP API version in this article the latest?
The cited HTTP guide documents version 24.04. Check PDFCrowd’s current documentation for the version to use; the research reviewed for this article does not establish which version is newest.


