Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk7 min

How to Generate PDFs from a Webpage with PDFShift in PHP

Send a URL or HTML string to PDFShift’s PDF conversion endpoint from PHP, authenticate with X-API-Key, check the response, and save the resulting PDF safely.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To generate a PDF with PDFShift in PHP, send a JSON POST request to https://api.pdfshift.io/v3/convert/pdf, set the source field to a webpage URL or HTML string, and authenticate with your API key in the X-API-Key header. Check the HTTP response before saving its body as a PDF.

Generate a PDF with PHP and cURL

This complete example reads the API key from an environment variable, submits a URL for conversion, and writes the successful response to webpage.pdf. The endpoint, JSON request, and authentication header follow PDFShift’s PHP guide. Set PDFSHIFT_API_KEY in your server environment before running it.

As an Amazon Associate I earn from qualifying purchases.

<?php
$apiKey = getenv('PDFSHIFT_API_KEY');
if (!$apiKey) {
    throw new RuntimeException('Set the PDFSHIFT_API_KEY environment variable.');
}

$params = [
    'source' => 'https://example.com',
];

$ch = curl_init('https://api.pdfshift.io/v3/convert/pdf');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($params, JSON_THROW_ON_ERROR),
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'X-API-Key: ' . $apiKey,
    ],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 90,
]);

$body = curl_exec($ch);
if ($body === false) {
    $error = curl_error($ch);
    curl_close($ch);
    throw new RuntimeException('PDFShift request failed: ' . $error);
}

$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($status < 200 || $status >= 300) {
    throw new RuntimeException('PDFShift returned HTTP ' . $status . ': ' . $body);
}

if (file_put_contents(__DIR__ . '/webpage.pdf', $body) === false) {
    throw new RuntimeException('Could not write webpage.pdf');
}

echo "Saved webpage.pdfn";

Replace https://example.com with a page PDFShift can access. The returned body is binary PDF data, so save it as a file or stream it with an appropriate PDF content type; do not print it as ordinary text. Keep the API key on the server, not in browser JavaScript or a public repository.

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

Choose a URL or raw HTML for source

Use a URL when the page is publicly reachable

Set source to the page URL when PDFShift should fetch and render the page. This is convenient when your PHP application does not already have the complete markup. The URL-based and raw-HTML approaches use the same request field.

Use raw HTML when your PHP application has the document

Set source to an HTML string when your application has generated the markup or the document is not publicly reachable. This also avoids having PDFShift make a separate request to retrieve the HTML itself. PDFShift recommends raw HTML and says that inlining CSS and JavaScript can reduce resource requests and conversion time; that is the vendor’s guidance, not a guaranteed timing result for every document.

$params = [
    'source' => '<!doctype html><html><head><style>body{font-family:sans-serif}</style></head><body><h1>Invoice</h1><p>Generated by PHP</p></body></html>',
];

For HTML that depends on external images, stylesheets, or scripts, make sure those assets are accessible to the conversion service. The PHP guide index has separate guides for URL conversion and CSS or JavaScript supplied as strings or URLs; consult the specific guide for the syntax of those options.

Use Guzzle if it is already in your PHP application

PDFShift’s PHP guide index documents both cURL and Guzzle approaches. The following Guzzle example uses the same endpoint, JSON payload, and API-key header; it writes the response only after checking the status. Install Guzzle through your project’s existing dependency manager if it is not already present.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<?php
require __DIR__ . '/vendor/autoload.php';

$apiKey = getenv('PDFSHIFT_API_KEY');
if (!$apiKey) {
    throw new RuntimeException('Set the PDFSHIFT_API_KEY environment variable.');
}

$client = new GuzzleHttpClient(['timeout' => 90]);
$response = $client->post('https://api.pdfshift.io/v3/convert/pdf', [
    'headers' => ['X-API-Key' => $apiKey],
    'json' => ['source' => 'https://example.com'],
    'http_errors' => false,
]);

$status = $response->getStatusCode();
$body = (string) $response->getBody();
if ($status < 200 || $status >= 300) {
    throw new RuntimeException('PDFShift returned HTTP ' . $status . ': ' . $body);
}

if (file_put_contents(__DIR__ . '/webpage.pdf', $body) === false) {
    throw new RuntimeException('Could not write webpage.pdf');
}

Choose the HTTP client your project already uses; PDFShift’s available guides do not establish a universal performance advantage for either library.

Authentication, response handling, and safe delivery

  • Send the current API-key header: use X-API-Key. PDFShift’s help article says unauthenticated requests can fall back to unauthenticated mode and receive a watermark. The article says the API moved to this header on 2025-05-06; older package examples may show a different authentication method. See PDFShift’s authentication help.
  • Check transport errors separately from HTTP errors: cURL can fail before receiving an HTTP response; check curl_exec() for false, then inspect the status code for an unsuccessful response.
  • Do not label every response as a PDF: only save or stream the body as PDF after confirming a successful status. On failure, preserve the error response for diagnosis rather than writing it to a file ending in .pdf.
  • Protect the key and output: load the key from server-side configuration or a secret store, and write files to a controlled location. If returning a PDF to a user, set download/inline headers and authorization according to your application’s needs.

For authenticated usage information, PDFShift’s help article identifies GET https://api.pdfshift.io/v3/credits/usage as a credits-usage check.

Options for documents that need more than a basic conversion

The PDFShift PHP guide index lists dedicated material for these cases. The index establishes that guides exist, but check the individual guide for exact option names and request syntax before adding parameters.

  • Page layout and content: custom headers and footers, full-height output, page selection, and custom-element waiting.
  • Styling and rendering: external or inline CSS and JavaScript, time limits, and behavior when the source fails to load.
  • Access and protection: custom HTTP headers, cookies, and PDF protection.
  • Delivery and workflow: webhooks, hosted PDF URLs, and direct Amazon S3 delivery.
  • Watermarks: text and image watermark options.

Start with the smallest request that produces the expected document, then add the relevant feature using its dedicated instructions in the PHP guide index.

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.

Troubleshoot common failures

Symptom Likely cause What to check
The request fails before an HTTP status is returned cURL transport, DNS, TLS, or connection failure Read curl_error(); check outbound network access and TLS configuration on the PHP host.
An error status comes back instead of a PDF Invalid request, inaccessible source, or another API-side error Log the status and response body securely. Confirm the JSON is valid and the URL can be reached by the service.
The PDF has a watermark The request may be unauthenticated Confirm the API key is present and sent as X-API-Key; consult the authentication guidance.
The PDF is missing images or styling Resources may be external or inaccessible to the renderer Check whether asset URLs are reachable and whether the page relies on scripts or styles not yet loaded. Consider raw HTML with inlined resources where appropriate.
The saved file is not a readable PDF An error response may have been written as binary output Check the HTTP status before saving; retain and inspect the response body on failure.
The conversion times out The page or its resources may take too long to load Review the page’s dependency on external resources and use the documented time-limit or custom-element-waiting guidance for the required behavior.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability, and cost considerations

For conversion speed, PDFShift’s own PHP guide recommends raw HTML and says that inlining CSS and JavaScript can reduce network requests and loading time. Actual duration depends on the page and its resources; no universal conversion time is established here. Set a client-side timeout appropriate to your application and handle failures rather than assuming each request will finish successfully.

PDFShift’s homepage, accessed in 2026, displays vendor-reported figures of 86+ million conversions, 56,000+ developers, a 1.5-second average conversion time, and 99.99% uptime. These are the company’s displayed claims, not independent measurements or a guarantee for an individual PHP request; see PDFShift’s homepage.

Or skip the browser setup

If your actual need is a screenshot rather than a paginated PDF, ScreenshotNeo returns a webpage screenshot in PNG, JPEG, or WebP, or a PDF, from one GET request. For a PDF capture, the API endpoint is https://api.screenshotneo.com/v1/shot; this PHP example saves the response as a file. See the ScreenshotNeo API documentation for request options.

<?php
$query = http_build_query([
    'access_key' => getenv('SCREENSHOTNEO_API_KEY'),
    'url' => 'https://example.com',
    'format' => 'pdf',
]);
$response = file_get_contents('https://api.screenshotneo.com/v1/shot?' . $query);
if ($response === false) {
    throw new RuntimeException('ScreenshotNeo request failed.');
}
file_put_contents(__DIR__ . '/webpage.pdf', $response);

ScreenshotNeo accepts cookie banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; those steps can be turned off. Bot checks/CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers identify the page verdict and billing status. It also offers an MCP server with take_screenshot, get_page_info, and capture_pdf tools for AI agents. 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.

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

Frequently Asked Questions

Can I convert HTML that is not publicly accessible?

Yes. Send the HTML string in the request’s source field instead of asking PDFShift to fetch a URL.

Does PDFShift document both cURL and Guzzle for PHP?

Yes. Its PHP guide index lists both client approaches; use the one that best fits your application.

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.

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.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

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.