With our PHP library you can use our HTML2PDF API to create PDFs in an easy way. It will take you only a few minutes to get started.

Quick Start

You can start producing PDF documents in a few minutes, by following these steps.

  1. Sign up for a license key (free trial available!)
  2. Set your default layout options in our members area
  3. Download our PHP library and use the included PHP example file to get started!

Here's a simple example of using the PHP library to convert a webpage to PDF.

<?php
  require 'html2pdf.php';

  $pdf = new HTML2PDF('yourlicensekey');
	
  $pdf->SetPageSize('A4');                     // Set page format to A4
  $pdf->SetPageOrientation('Portrait');        // Set page orientation to 'Portrait'
	
  $pdf->CreateFromURL('www.example.com');      // Convert the page www.example.com to PDF
  
  $pdf->Display();                             // Display the PDF for download 

If you'd rather convert HTML to PDF and save the PDF locally, then you can use the below code instead.

<?php
  require 'html2pdf.php';

  $pdf = new HTML2PDF('yourlicensekey');
  
  $pdf->CreateFromHTML('Your HTML here');      // Convert raw HTML to PDF
  
  $pdf->Save('/files/yourfile.pdf');           // Save the PDF as local file

As you can see, the PHP library is very simple to use and has straightforward functions. In the next paragraphs we'll show you which functions you can use to get the layout of your PDFs just the way you want it.

Setting Options

All our API options can be quickly set in our members area with an easy-to-use WYSIWIG screen and we recommend you to start with that. Once you've set these defaults, they will be used for all HTML2PDF API calls from that point on.

Still, if you need to set specific options, then you can override these by using the below HTML2PDF library functions.

NOTE: if you want to set options with the PHP library, then you should always use the library functions before calling the CreateFromURL or CreateFromHTML functions.

Page Sizes and Margins

You can change the size, orientation and margins of your PDF by use the following PHP functions.

We have many different standard page sizes, but you can also define your own page size by using the width and height parameters.

Page size, orientation and margin options
FunctionDescription
SetPageSizeset the page size to a standard page format like A4, B0, Letter etc
SetPageOrientationset the orientation to either portrait or landscape
SetPageDimensionsuse exact dimensions for the page size
SetDimensionUnitset the unit of measure for dimensions to mm, cm, in or px
SetMarginsset the margins
SetViewportset the viewport (default is 1366 by 768)

Layout Settings

By default we try to convert the webpage (or HTML) to PDF exactly as it would look on screen. Below we have some functions that you can use to adjust the layout of your page.

Functions for a different or better layout
ParameterDescription
SetCssMediaTypeUse the Print Layout or the Screen layout as source for the PDF
OptimizeLayoutOptimize fonts and colors in the PDF and make sure static items only occur once
LazyLoadLoad the page "lazily" so that all content appears as if you've scrolled down the page
SetWaitTimeWait for a certain amount of time in msec after page load, for example for redirections or JavaScript loading
SetCustomCSSUse custom CSS to overwrite the default styles of your page

Here are some examples of changing the layout with these function calls.

require 'html2pdf.php';
$pdf = new HTML2PDF('yourlicensekey');
	                                             
$pdf->SetCssMediaType('print');                // Use the print layout of the webpage
$pdf->LazyLoad();                              // Load lazy content
$pdf->SetCustomCss('#header {display:none;}'); // Hide the DIV with ID header

Headers and Footers

You can use a custom header and/or footer on your PDFs with the functions below. On our API documentation page you'll find out which special tags you can use in the header and footer to include automated information like the page number, the URL and more.

Parameters for header and footer
ParameterDescription
SetHeaderDefine the header of the PDF in HTML
SetFooterDefine the footer of the PDF in HTML
SetPageOffsetDefine the offset for page numbering

Here are some examples of these function calls in action.

require 'html2pdf.php';
$pdf = new HTML2PDF('yourlicensekey');
	                                             
$pdf->SetHeader('<center>%page</center>');   // Show the page number in the center
$pdf->SetFooter('Title: %title - %MM/%DD');  // Show the title and month/day of PDF creation
$pdf->PageOffset(2);                         // Start page numbering at 3 instead of 1

Watermarks and Backgrounds

The following functions allow you to put a watermark over your PDFs or underneath your content, in which case it's a background.

Watermark and Background Functions
ParameterDescription
SetWatermarkLocationSet the position of the watermark
SetWatermarkTransformationSet rotation, opacity and scaling of the watermark
SetWatermarkImageDefine the URL where the watermark can be found
SetWatermarkTextSet the text and font characteristics of the watermark
SetStationaryLocationSet the postion of the stationary background
SetStationaryTransformationSet rotation, opacity and scaling of the background
(set scaling to 0 for a full background)
SetStationaryImagesDefine the URL(s) of the stationary image(s)

Rights Management

Our PHP library has the following functions to protect your PDFs with passwords and against printing, content copying and annotation.

Functions for PDF encryption and rights management
FunctionDescription
SetEncryptionLevelSet the encryption level for the PDF
SetPasswordsSet the owner password and the 'document open password'
SetPermissionsSet the permissions on the PDF

Note that we recommend at least 128-bit AES if you want to encrypt your PDF. The RC4 encryption levels are merely used for backwards compatibility, but are generally considered unsafe.

Other Options

Below are the remaining functions that you can use to set options with the PHP library.

Other functions of the HTML2PDF PHP library
ParameterDescription
SetEndPointuse a different server for conversions
SetGrayscaleforce a PDF in grayscale
NoBackgroundremove the background
NoInternalLinksdisable links within the domain
NoExternalLinksdisable links to external sites
NoAdsdisable ads on webpages
SetTitleset the title of the PDF
SetZoomFactorset the zoom factor of the PDF
ActivateDebuggingactivates more detailed logging on our server for debugging purposes

Exception Handling

We recommend that you use a try/catch block when you use our HTML2PDF library. In that way you can handle exceptions gracefully.

You can do this as follows.

try {

   $pdf = new HTML2PDF('yourlicensekey');
   $pdf->CreateFromURL('https://www.example.com');
   $pdf->Display();
   
} catch (Exception $error) {

   // now you can handle the exception:
   echo $error->getMessage();
   echo $error->getCode();
   
}

The table below shows which exceptions you can receive and what they mean.

CodeDescription
401 Authorization requiredYou specified an invalid license key
429 Too Many RequestsYou have overrun the limit for your plan
503 Service unavailableYou are sending multiple requests at the same time to the API from the same IP address
520 Invalid page size or marginsYou have set your page size and/or margins in such a way that the page has become too small or large to print on
530 DNS Error for URLThe domain of the URL can not be found
8xx cURL errorcURL is trying to connect to our server, but there's a problem on your side with the cURL function.
Please check the exact 8xx code for more information.
900 URL is invalidYou should pass a valid URL. URLs can start with http:// or https:// or have no prefix like www.google.com.
901 HTML string can not be emptyYou must pass HTML code. Therefore do not try to pass an empty string.
905 Watermark not validYou must pass a URL that points to an image if you want to use an image as watermark.
Check if your URL really points to your watermark image.
906 Watermark text can not be emptyYou must pass a real text if you want to use a text watermark.
Therefore do not try to pass an empty string.
907 Stationary not validYou must pass valid URLs that point to an image if you want to use one or more images as stationary.
Check if your URLs really point to your stationary images.
910 Filename does not existThe file you're trying to send does not exist as the filename you specified.
Please make sure to include the full path in your filename.
911 File can not be emptyThe file you're trying to send does not contain any data.
920 Not possible to save PDF fileYou're most likely out of space on your system and are not able to save the file locally.
930 cURL is not installedYou need cURL on your system to be able to work with the PHP library.
Please follow the installation instructions from PHP.net.
940 Access errorBy default we use your system's temp directory to save the PDF you receive from us.
If you web user does not have access to that directory you should either change that user's rights or use the function SetTempDirectory to change the directory we need to use.
990 We could not load this pageThere's a problem with the URL you're trying to convert.
It may not be available currently or it may contain incorrect client side scripting, flash or other things.

Getting Help

Service is our number one priority. We feel an API is only useful not only if it's reliable, but also if you can resolve issues fast and frictionless. That's why we respond very quickly to support requests.

It would be very helpful if you activate debugging in your script so that we can do more extensive error tracking on our end. You can do so with the following command in your script.

$pdf->ActivateDebugging();

After running your script, you can then just send an email to our support email address.

Please try to include the following:

  • Your license details
  • Your PHP code or the actual PHP file
  • A short description of your problem
  • A screenshot of your settings
  • The exception and/or the PDF that you received