Convert HTML To PDF in PHP
Convert HTML To PDF in PHP
Pdfcrowd Blog
Product updates, tips & tricks
Blog archive »
Introduction
Let's start with an example:
<?php
require 'pdfcrowd.php';
This code converts en.wikipedia.org and stores the generated PDF to a string
variable. You can save the result to a file or you can stream it to the browser, which
we will discuss in detail shortly. You can click the thumbnail to open the generated
PDF file:
Besides web pages, you can also convert a local HTML file or an HTML string:
<?php
$pdf = $client->convertFile('/path/to/your/file.html');
$pdf = $client->convertString('<b>bold</b> and <i>italic</i>');
?>
<?php
$client->convertUrlToFile('http://example.com/', 'example.pdf');
?>
Basic Customization
Now that you know the basics, you may want to customize the generated PDF.
Let's change the page format to Letter with half-inch margins:
<?php
$client->setPageSize("Letter");
$client->setPageMargins("0.5in", "0.5in", "0.5in", "0.5in");
?>
<?php
$client->setPageMargins("1cm", "1cm", "10mm", "10mm");
?>
You can also specify the appearance of the PDF when it is opened in a viewer:
<?php
$client->setInitialPdfZoomType(Pdfcrowd::FIT_PAGE);
$client->setPageLayout(Pdfcrowd::CONTINUOUS);
?>
The API provides many other options including password protection and fully
customizable page headers and footers. Learn more about the available options in
the HTML to PDF API - PHP SDK documentation.
<?php
require 'pdfcrowd.php';
try {
$client = new \Pdfcrowd\HtmlToPdfClient("username", "apikey");
$pdf = $client->convertUrl("https://example.com.com/");
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");
}
?>
<?php
$pdf = $client->convertString("<html><head>..</head><body>..</body></html>");
?>
<?php
header("Content-Disposition: attachment; filename=\"mydomain.pdf\"");
?>
<?php
require 'pdfcrowd.php';
function generatePDF()
{
if (!$_GET["pdf"])
return False;
try {
try {
// build 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, '', '&');
}
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
yes, then the 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.
<?php
if (generatePDF())
return;