Introduction

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>');?>

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.

Server Side PDF Generation

In this section we will show two common PDF generation scenarios.

Generate PDF and send it to the browser

The following code converts example.com to PDF and sends it as a
response:

Provide a PDF version of your web pages

This example shows how to enhance your PHP code so it can return a PDF
version of your web pages. Let's look at the following helper function:

<?phprequire'pdfcrowd.php';functiongeneratePDF(){if(!$_GET["pdf"])returnFalse;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,'','&');}// call the API$client=new\Pdfcrowd\HtmlToPdfClient("username","apikey");$pdf=$client->convertUrl($url);// send the generated pdf to the browserheader("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");}returnTrue;}?>

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.

You can use the function in your code like this:

<?phpif(generatePDF())return;// your HTML rendering code// ...?>

https://mydomain.com/page.php?pdf=1 now returns a PDF version of
https://mydomain.com/page.php.