Introduction

This code converts bbc.co.uk and stores the generated PDF to a
string. 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_from_file=$client->convertFile('/path/to/your/file.html');$pdf_from_html=$client->convertHtml('<b>bold</b> and <i>italic</i>');?>

It is also possible to save the PDF directly to a file by passing a
file pointer as the second argument:

The API provides many other options including password protection and fully customizable
page headers and footers. You can find the complete PHP API reference
here.

Error Handling

The API should not never return a corrupted PDF. If the service can't
for some reason generate a valid PDF then an instance of
PdfcrowdException is thrown. Therefore it is highly recommended to
enclose your code within a try-catch block:

<?phptry{// ...}catch(PdfcrowdException$why){echo"FAILED: ".$why;}?>

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 mydomain.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=newPdfcrowd("username","apikey");$pdf=$client->convertURI($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(PdfcrowdException$why){echo"PDF creation failed: ".$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// ...?>

Now when you enter

http://mydomain.com/page.php?pdf=1

the browser returns a PDF version of the page.

Try Out The API

You can sign up for a free trial
account, download
the API client library for your favorite language and start creating PDF from web
pages or raw HTML in just a few minutes. Pdfcrowd supports PHP, Java, Ruby,
Python, .NET, node.js, Bash, and HTTP POST.