Frameworks · Updated 2026-12-03
Generate PDFs in PHP and WordPress
This guide turns an array of data into a finished PDF from PHP. You post a template id and your data to one endpoint and get the file back. There is no PDF library to install and no browser on your server, so it works on shared hosting, a VPS or a container. The documents render in a current version of Chrome, so modern CSS and every script work.
You need PHP 7.4 or later with the cURL extension, and a DevilPDF API key. The free plan includes 500 documents a month.
Using Laravel? It has its own guide: Generate PDFs in Laravel.
#1. Get an API key
Sign up, open API keys in the dashboard and create a key. It starts with dp_live_. Keep it in an environment variable, never in code you commit:
export DEVILPDF_API_KEY="dp_live_..."On most hosts you can set it in the PHP-FPM pool, the Apache SetEnv directive or your hosting panel. PHP reads it with getenv('DEVILPDF_API_KEY').
#2. Render with cURL
Every account can use seven starter templates: invoice, quote, receipt, statement, report, packing-slip and certificate. This function renders any of them and returns the PDF bytes:
<?php
function devilpdf_render(array $body): string
{
$key = getenv('DEVILPDF_API_KEY');
if (!$key) {
throw new RuntimeException('DEVILPDF_API_KEY is not set.');
}
$ch = curl_init('https://devilpdf.com/v1/render');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $key,
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode($body + ['output' => 'file'], JSON_THROW_ON_ERROR),
]);
$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($response === false) {
throw new RuntimeException('Request failed: ' . $curlError);
}
if ($status !== 200) {
$error = json_decode($response, true)['error'] ?? ['type' => 'unknown', 'message' => "HTTP $status"];
throw new RuntimeException($error['type'] . ': ' . $error['message']);
}
return $response;
}"output": "file" makes the response body the PDF itself, and nothing is stored on DevilPDF's side. Errors still come back as JSON with an error object holding a type and a message, so check the status before you treat the body as a file.
Now save an invoice to disk:
<?php
require __DIR__ . '/devilpdf.php';
$pdf = devilpdf_render([
'template' => 'invoice',
'data' => [
'number' => 'INV-1001',
'issue_date' => '2026-12-03',
'due_date' => '2027-01-02',
'company' => ['name' => 'Northwind Studio', 'address' => "410 Bay Street\nToronto, ON M5H 2Y4"],
'customer' => ['name' => 'Acme Robotics Inc.', 'address' => "2200 Mission Street\nSan Francisco, CA 94110"],
'items' => [
['name' => 'Brand identity system', 'quantity' => 1, 'unit_price' => 4800],
['name' => 'Front-end development', 'description' => 'Billed hourly', 'quantity' => 46, 'unit_price' => 135],
],
'tax_rate' => 13,
'tax_label' => 'HST',
],
'filename' => 'INV-1001',
]);
file_put_contents(__DIR__ . '/invoice.pdf', $pdf);
echo 'Saved invoice.pdf (' . strlen($pdf) . " bytes)\n";Run it with php save.php. The template adds up the line items, tax and total itself, so you never send totals. To see every field a starter accepts, fetch it and read sample_data:
curl https://devilpdf.com/v1/templates/invoice \
-H "Authorization: Bearer $DEVILPDF_API_KEY"If you would rather get a link than the bytes, leave output out. The response is then JSON with the document id, the page count in pages and a signed download link in url.
#3. The same call with Guzzle
If your project already uses Composer, Guzzle does the same in fewer lines:
composer require guzzlehttp/guzzle<?php
require __DIR__ . '/vendor/autoload.php';
use GuzzleHttp\Client;
function devilpdf_render(array $body): string
{
$client = new Client(['timeout' => 60]);
$res = $client->post('https://devilpdf.com/v1/render', [
'headers' => ['Authorization' => 'Bearer ' . getenv('DEVILPDF_API_KEY')],
'json' => $body + ['output' => 'file'],
'http_errors' => false,
]);
if ($res->getStatusCode() !== 200) {
$error = json_decode((string) $res->getBody(), true)['error'] ?? null;
throw new RuntimeException($error ? $error['type'] . ': ' . $error['message'] : 'HTTP ' . $res->getStatusCode());
}
return (string) $res->getBody();
}The json option encodes the array and sets Content-Type: application/json. http_errors => false stops Guzzle from throwing on a 4xx, so you can read DevilPDF's error message yourself.
#4. Send the PDF to the browser
To let a user open or download the PDF, render it on the server and send it with the right headers. The API key never leaves your server.
<?php
require __DIR__ . '/devilpdf.php';
// Look up the invoice the signed-in user is allowed to see.
$invoice = load_invoice_for_current_user($_GET['id'] ?? '');
if (!$invoice) {
http_response_code(404);
exit('Not found');
}
try {
$pdf = devilpdf_render(['template' => 'invoice', 'data' => $invoice]);
} catch (RuntimeException $e) {
error_log($e->getMessage());
http_response_code(502);
exit('The invoice could not be generated. Please try again.');
}
$filename = 'invoice-' . preg_replace('/[^A-Za-z0-9_-]/', '', $invoice['number']) . '.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Length: ' . strlen($pdf));
header('Cache-Control: private, no-store');
echo $pdf;
exit;load_invoice_for_current_user() stands for your own lookup, which should check that the invoice belongs to the person asking. Use inline to open the PDF in the browser tab, or attachment to download it. The filename is stripped to safe characters before it goes into a header.
Send the headers before any other output. A stray space or a BOM before <?php breaks them.
#5. WordPress and WooCommerce
In WordPress, use wp_remote_post instead of cURL. It respects your site's proxy and SSL settings and needs no extension.
Put the key in wp-config.php, above the line that says to stop editing. Reading it from the environment keeps it out of the file as well:
define( 'DEVILPDF_API_KEY', getenv( 'DEVILPDF_API_KEY' ) );Then add a small plugin. It registers an admin-post.php action that renders a WooCommerce order as an invoice and sends it to the browser. Only shop managers and the customer who placed the order can download it, and every link carries a nonce.
<?php
/**
* Plugin Name: DevilPDF invoices
* Description: PDF invoices for WooCommerce orders, rendered by DevilPDF.
*/
defined( 'ABSPATH' ) || exit;
/** Render a document and return the PDF bytes, or a WP_Error. */
function devilpdf_render( array $body ) {
if ( ! defined( 'DEVILPDF_API_KEY' ) || ! DEVILPDF_API_KEY ) {
return new WP_Error( 'devilpdf_no_key', 'DEVILPDF_API_KEY is not set.' );
}
$response = wp_remote_post( 'https://devilpdf.com/v1/render', array(
'timeout' => 60,
'headers' => array(
'Authorization' => 'Bearer ' . DEVILPDF_API_KEY,
'Content-Type' => 'application/json',
),
'body' => wp_json_encode( $body + array( 'output' => 'file' ) ),
) );
if ( is_wp_error( $response ) ) {
return $response;
}
$status = (int) wp_remote_retrieve_response_code( $response );
$bytes = wp_remote_retrieve_body( $response );
if ( 200 !== $status ) {
$json = json_decode( $bytes, true );
$type = $json['error']['type'] ?? 'error';
$error = $json['error']['message'] ?? 'HTTP ' . $status;
return new WP_Error( 'devilpdf_' . $type, $error );
}
return $bytes;
}
/** A signed link to an order's invoice. */
function devilpdf_invoice_url( $order_id ) {
$url = add_query_arg(
array( 'action' => 'devilpdf_invoice', 'order_id' => absint( $order_id ) ),
admin_url( 'admin-post.php' )
);
return wp_nonce_url( $url, 'devilpdf_invoice_' . absint( $order_id ) );
}
add_action( 'admin_post_devilpdf_invoice', 'devilpdf_invoice_download' );
function devilpdf_invoice_download() {
$order_id = isset( $_GET['order_id'] ) ? absint( $_GET['order_id'] ) : 0;
check_admin_referer( 'devilpdf_invoice_' . $order_id );
$order = wc_get_order( $order_id );
if ( ! $order ) {
wp_die( 'Order not found.', '', array( 'response' => 404 ) );
}
$customer_id = $order->get_customer_id();
$is_owner = $customer_id && $customer_id === get_current_user_id();
if ( ! $is_owner && ! current_user_can( 'edit_shop_orders' ) ) {
wp_die( 'You are not allowed to download this invoice.', '', array( 'response' => 403 ) );
}
$items = array();
foreach ( $order->get_items() as $item ) {
$items[] = array(
'name' => $item->get_name(),
'quantity' => $item->get_quantity(),
'unit_price' => (float) $order->get_item_total( $item, true ),
);
}
$shipping = (float) $order->get_shipping_total() + (float) $order->get_shipping_tax();
if ( $shipping > 0 ) {
$items[] = array( 'name' => 'Shipping', 'quantity' => 1, 'unit_price' => $shipping );
}
$address = array_filter( array(
$order->get_billing_company(),
$order->get_billing_address_1(),
$order->get_billing_address_2(),
trim( $order->get_billing_postcode() . ' ' . $order->get_billing_city() ),
$order->get_billing_country(),
) );
$created = $order->get_date_created();
$locale = implode( '-', array_slice( explode( '_', determine_locale() ), 0, 2 ) );
$pdf = devilpdf_render( array(
'template' => 'invoice',
'locale' => $locale,
'data' => array(
'number' => $order->get_order_number(),
'issue_date' => $created ? $created->date( 'Y-m-d' ) : gmdate( 'Y-m-d' ),
'currency' => $order->get_currency(),
'company' => array( 'name' => get_bloginfo( 'name' ) ),
'customer' => array(
'name' => $order->get_formatted_billing_full_name(),
'address' => implode( "\n", $address ),
),
'items' => $items,
),
) );
if ( is_wp_error( $pdf ) ) {
error_log( 'DevilPDF: ' . $pdf->get_error_message() );
wp_die( 'The invoice could not be generated. Please try again.', '', array( 'response' => 502 ) );
}
$filename = 'invoice-' . sanitize_file_name( $order->get_order_number() ) . '.pdf';
nocache_headers();
header( 'Content-Type: application/pdf' );
header( 'Content-Disposition: inline; filename="' . $filename . '"' );
header( 'Content-Length: ' . strlen( $pdf ) );
echo $pdf; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- binary PDF.
exit;
}
/** Add an "Invoice" button to each order in My Account > Orders. */
add_filter( 'woocommerce_my_account_my_orders_actions', function ( $actions, $order ) {
$actions['devilpdf_invoice'] = array(
'url' => devilpdf_invoice_url( $order->get_id() ),
'name' => 'Invoice',
);
return $actions;
}, 10, 2 );Activate it under Plugins. A few notes on the code:
admin_post_devilpdf_invoiceonly runs for signed-in users. Guests get nothing, which is what you want for invoices.check_admin_referer()stops the request unless the link's nonce is valid for this user and this order. The capability check then decides who may see it. Keep both.- WooCommerce can apply a different tax rate to each line, so this example sends unit prices with tax included (
get_item_total( $item, true )) and notax_rate. If your shop charges one rate, send prices without tax and addtax_rateandtax_label, and the template adds the tax line for you. Fees and refunds are left out to keep the example short. - The
localecomes from the site language, so a French shop gets French labels, dates and money. Arabic, Hebrew, Persian and Urdu sites also get the page laid out right to left. See languages and locales.
To link to the invoice from anywhere else, such as an admin screen or an email to a signed-in customer, call devilpdf_invoice_url( $order_id ).
Not on WooCommerce? Keep devilpdf_render() and the admin_post_ handler, replace wc_get_order() with your own lookup, and check a capability such as current_user_can( 'manage_options' ) before rendering.
#Many documents at once
For hundreds of PDFs, such as a month of invoices, do not loop over /v1/render and wait on each one. Send them to POST /v1/render/batch in one request and get a webhook when they finish. In WordPress, run that from WP-Cron or WP-CLI, not from a page load. See async and batch.
When something fails, branch on error.type, not the message. rate_limited, render_timeout and internal_error are worth one retry; the rest need the request fixed. A failed render never counts against your documents. See errors.
#Next steps
- Quickstart: the same request in curl, Node, Python, Go and Ruby.
- Render reference: every field, including page size, password protection and image output.
- Templates: copy a starter and make it yours.
- Generate PDFs in Laravel and in Node.js.
- Get a free API key