Adding a custom header or footer in PHP with Guzzle
In this guide, we'll show you how to add custom headers or footers to a PDF using PHP and the Guzzle library.
We'll focus this guide on the
header
parameter, but know that the
footer
parameter works
exactly
the same way.
The
header
parameter is an object that accepts the following parameters:
-
source: The source of the header. It can be a URL or a raw HTML document. You can also provide some variables that we'll explain at the bottom of this guide. -
height: The height of the header. By default, the height is in pixels, but you can also usemm,cmorinas units, like10mm. -
start_at: The page number where the header should start. By default, the header will start at the first page.
NOTE : You must provide the full data in the header/footer, and not via a network request. Loading files such as external CSS, Js or Fonts won't work in the header or footer. Instead, we recommend you to embed them in Base64.
Here's an example:
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
# You can get an API key at https://pdfshift.io
$api_key = 'sk_xxxxxxxxxxxx'
$params = array (
'source' => 'https://en.wikipedia.org/wiki/PDF',
'header' => array (
'source' => '<div>Page {{ page }} over a total of {{ total }}. Made on {{ date }}</div>',
'height' => 150,
'start_at' => 2
// Create a Guzzle client
$client = new Client();
try {
// Make the POST request
$response = $client->post('https://api.pdfshift.io/v3/convert/pdf', [
'headers' => [
'Content-Type' => 'application/json',
'X-API-Key' => $api_key
'json' => $params
// Get the response body
$body = $response->getBody()->getContents();
// Save the file to result.pdf
file_put_contents('result.pdf', $body);
echo 'The PDF document was generated and saved to result.pdf';
} catch (RequestException $e) {
if ($e->hasResponse()) {
$statusCode = $e->getResponse()->getStatusCode();
$reasonPhrase = $e->getResponse()->getReasonPhrase();
throw new Exception("Request failed with status code $statusCode: $reasonPhrase");