In this guide, we'll explore how to efficiently convert web pages and HTML content to PDF using the Pdfcrowd HTML to PDF API in a PHP server environment. This capability is essential for developers looking to enhance their applications with dynamic PDF generation features.
Setting Up Pdfcrowd in Your PHP Project
Before you start coding, make sure to install the Pdfcrowd API client library in your project. Installation instructions are available on the PHP API Client Library page.
Here's a straightforward example to get you started:
require 'pdfcrowd.php';
$client = new \Pdfcrowd\HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");
$pdf = $client->convertUrl('https://example.com/');
This script fetches the content from the specified URL and converts it into a PDF stored as a string variable, $pdf
. The content of the variable can be saved to a PDF file or sent in a response to the browser, which we will describe in detail later.
This code uses demo credentials, but you can replace these with your personal API credentials by registering with Pdfcrowd.
Customizing Your PDF Output
You can easily adjust the appearance and size of your PDFs using simple API calls:
$client->setPageSize("Letter");
$client->setPageMargins("0.5in", "0.5in", "0.5in", "0.5in");
// Use metric units if preferred:
$client->setPageMargins("1cm", "1cm", "10mm", "10mm");
Further enhance how the PDF appears in viewers:
$client->setInitialPdfZoomType(Pdfcrowd::FIT_PAGE);
$client->setPageLayout(Pdfcrowd::CONTINUOUS);
For a complete list of customization options, refer to the API method reference.
Converting HTML Content
Apart from web pages, the Pdfcrowd API also lets you convert HTML from local files or directly from strings:
$pdf = $client->convertFile('/path/to/your/file.html');
$pdf = $client->convertString('<p>Hello, world!</p>');
These methods are useful for applications that need to generate PDFs from various HTML sources.
The API can also render HTML templates by expanding them with data before converting to PDF:
$api->setDataFile("data.json");
$pdf = $api->convertFile("invoice_template.html");
Server-Side PDF Generation
In this section, we will demonstrate two common server-side PDF generation scenarios.
Generate PDF and send it to the browser
The following code converts a webpage and sends the generated PDF directly to the browser:
<?php
require 'pdfcrowd.php';
try {
$client = new \Pdfcrowd\HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");
$pdf = $client->convertUrl("https://your-site.com/?reportID=181605");
header("Content-Type: application/pdf");
header("Cache-Control: no-cache");
header("Accept-Ranges: none");
header("Content-Disposition: inline; filename=\"example.pdf\"");
echo $pdf;
}
catch(\Pdfcrowd\Error $why) {
fwrite(STDERR, "Pdfcrowd Error: {$why}\n");
}
?>
This functionality is particularly useful for dynamically generating documents such as invoices, reports, and personalized documents. You can also use the convertFile()
or convertString()
methods in this situation.
Enable on-the-fly PDF conversion of your webpages
You can automate the process to offer a PDF version of web pages on demand using the generatePDF()
helper function:
<?php
require 'pdfcrowd.php';
function generatePDF()
{
if (!$_GET["pdf"])
return False;
try {
// form the url and remove the pdf field from the query string
$url = "http://" . $_SERVER["SERVER_NAME"] . $_SERVER["PHP_SELF"];
if (count($_GET) > 1) {
unset($_GET["pdf"]);
$url = $url . "?" . http_build_query($_GET, '', '&');
}
// call the API
$client = new \Pdfcrowd\HtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d");
$pdf = $client->convertUrl($url);
// send the generated pdf to the browser
header("Content-Type: application/pdf");
header("Cache-Control: no-cache");
header("Accept-Ranges: none");
header("Content-Disposition: attachment; filename=\"created.pdf\"");
echo $pdf;
}
catch(\Pdfcrowd\Error $why) {
fwrite(STDERR, "Pdfcrowd Error: {$why}\n");
}
return True;
}
?>
The generatePDF()
function first checks if there is a 'pdf' field in the query string. If present, this field is removed from the URL. The function then passes the modified URL to the API and finally sends the generated PDF to the browser.
You can use the function in your code as follows:
<?php
if (generatePDF())
return;
// Normal HTML page rendering follows
// ...
?>
Accessing https://your-site.com/page.php?pdf=1
now returns a PDF version of https://your-site.com/page.php
.
Resources
- HTML to PDF - PHP Guide
- PHP API Method Reference
- Convert HTML to PDF in PHP video tutorial
- Simple PHP web server example on GitHub
Updated April 24, 2024