PHP library for webpage or HTML to PDF conversion

We have created a PHP library that can handle the full functionality of our API. It's a class that lets you use all the options and functionality easily and has built in exception handling. You should have your first example working within 5 minutes!

You can download the library from our website at or install it via composer.

Usage via Composer

If you're using composer / Packagist in your project then you can install our PHP library as follows.

$ composer require pdfmyurl/pdfmyurl

The install will include an example.php file with a basic example as well as the library itself. Since namespacing is a bit different when you use composer, a basic URL to PDF conversion example would be as follows.

  require 'vendor/autoload.php';

  use pdfmyurl\pdfmyurl\PDFmyURL;

  // first fill in the license that you received upon sign-up
  $pdf = new PDFmyURL ('yourlicensekey');
  // now set the options, so for example when we want to have a page in A4 in orientation portrait
  // you can also set these in our members area with a Wysiwig form by the way
  // then do the conversion - this is how you convert Google to PDF and display the PDF to the user
  $pdf->CreateFromURL ('');
  // if you'd like to convert raw HTML instead you would have done this
  // $pdf->CreateFromHTML('<html><body>Hello World!</body></html>');
  // $pdf->Display();			

Usage via self-installing the library

If you don't use composer, you can simply download the PHP library and include it in your project. You can then use our API in PHP as in the following example:

  require 'pdfmyurl.php';

  $pdf = new PDFmyURL ('yourlicensekey');     // initialize the class with your license
  $pdf->SetPageSize('A4');                     // Set page format to A4
  $pdf->SetPageOrientation('Portrait');        // Set page orientation to 'Portrait'
  $pdf->CreateFromURL ('');      // Convert the Google Homepage to PDF
  $pdf->Display();                             // Display the PDF for download to the user

Below is a list of functions that you can use, as well as all the exceptions that you may encounter when you're using the library. This will help you quickly take full advantage of our webpage / HTML to PDF API.

You will use the functions of the library in the following sequence:

  1. Set options such as page size, margins, headers etc.
  2. Execute the conversion from a URL or HTML
  3. Display or save the PDF

Functions for setting options

Below is a list of all functions that you can use to set options for the conversion, the page layout and dimensions, margins, headers and footers, watermarking and much more.

The following functions allow you to customize the page dimensions and margins of your PDFs.

SetPageSize$pagesizeset the page size to one of the standard page formats like A4, B0, Letter etc
SetPageOrientation$orientationset the orientation to either portrait or landscape
SetPageDimensions$width, $heightset the page size to exact dimensions or force a single page PDF
SetDimensionUnit$unitset the unit of measure for custom dimensions to mm, cm, in or px
SetMargins$top,bottom,$left,$rightset the margins
SetViewport$width, $heightset the viewport, which by default is 1366 by 768

Below are some examples that show how to use these functions.

require 'pdfmyurl.php';                      // include the class
$pdf = new PDFmyURL ('yourlicensekey');      // initialize the class with your license
$pdf->SetPageSize('A4');                     // Set page format to A4
$pdf->SetPageOrientation('Portrait');        // Set page orientation to 'Portrait'
$pdf->SetDimensionUnit('mm');                // Set unit of measurement to millimeter
$pdf->SetPageDimensions(100, 200);           // Set the page to be 100mm wide and 200mm high
$pdf->SetPageDimensions(300, 0);             // Set the page to be 300mm wide and force a single long page
$pdf->SetMargins(10,10,5,5);                 // Set the top & bottom margin to 10mm and the left & right margin to 5mm
$pdf->SetViewport(800,600);                  // Use a viewport of 800*600 for rendering

The following functions allow you to customize the headers and footers of your PDFs. You can use HTML tags in the header & footer as longs as you don't use the <html> or <body> tags.

There are a number of special parameters you can use that help you set the page number, title, date and other relevant data in the header & footer - please check the documentation on headers and footers.

SetHeader$headerDefine the header of the PDF in HTML
SetFooter$footerDefine the footer of the PDF in HTML
SetPageOffset$offsetDefine the offset for page numbering

Below are some examples that show how to use these functions.

require 'pdfmyurl.php';                      // include the class
$pdf = new PDFmyURL ('yourlicensekey');      // initialize the class with your license
$pdf->SetHeader('<center>%page</center>');   // Set a header with the page number in the center
$pdf->SetFooter('Title: %title - %MM/%DD');  // Set a footer that shows the title and the month/day of PDF creation
$pdf->PageOffset(2);                         // Add 2 to the page number, this starts page numbering at 3 instead of 1

The following functions allow you to update the CSS styles of your page or show or hide specific parts of your webpage for the conversion. See the documentation on partial page conversion for more info.

SetCustomCSS$cssApply custom CSS to the page that's being converted
ShowContent$divsShow only content with this/these DIV id(s)
HideContent$divsHide all content with this/these DIV id(s)

Please note that for the ShowContent and HideContent functions DIV ids are case-sensitive and should be exactly passed as they are spelled.

Below are some examples that show how to use these functions.

require 'pdfmyurl.php';                      // include the class
$pdf = new PDFmyURL ('yourlicensekey');      // initialize the class with your license
$pdf->SetCustomCSS('* { margin:0px;}');      // Set 0 margins to all styles in the webpage                                           
$pdf->ShowContent('Main');                   // Show only the content of the DIV with id Main
$pdf->HideContent(array('header', 'footer'));// Hide the DIVs with ids header and footer

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

SetWatermarkLocation$x, $ySet the position of the watermark
SetWatermarkTransformation$angle,$opacity,$scaling_x,$scaling_ySet rotation, opacity and scaling of the watermark
SetWatermarkImage$urlDefine the URL where the watermark can be found
SetWatermarkText$text,$fontname,$fontcolor,$fontsizeDefine the text and font characteristics of the watermark
SetStationaryLocation$sx, $sySet the postion of the stationary background
SetStationaryTransformation$angle,$opacity,$scaling_x,$scaling_ySet rotation, opacity and scaling of the stationary - set scaling to 0 for FULL BACKGROUND DISPLAY
SetStationaryImages$url1, $url2, $url3Define the URL of the stationary images for first page, next pages and last page

The following functions allow you to protect your PDFs with passwords and against printing, content copying and annotation.

SetEncryptionLevel$levelSet the encryption level for the PDF, e.g. 256 (for 256bit aes)
SetPasswords$owner, $userSet the owner password and the 'document open' password
SetPermissions$print, $modify, $copySet the permissions on the PDF for everyone except the owner

The following functions allow you to define the way we can access your URLs in secure member areas.

SetHttpAuthentication$username, $passwordSet user name and password for basic HTTP Authentication
SetFormAuthentication$form_url, $form_fieldsSet parameters for login authentication via a form
SetSessionID$jsessionidSet a cookie with the JSESSIONID
SetCookieJar$cookiejarSet the contents of a cookie jar
SetNetscapeCookieJar$cookiejarSet the contents of a cookie jar in the old Netscape format

The following functions allow you to set various other options to control the conversion.

SetEndPoint$endpointselect a different server to do the conversions
SetPdfCreatorVersion$versionselect a different version of our PDF creator than your default
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 before grabbing the PDF
SetWaitTime$waitwait for this amount of time in msec after page load, for example for redirections
SetGrayscaleforce a PDF in grayscale
NoJavaScriptdisable JavaScript
SetJavaScriptDelay$delayset the amount of time in msec that JavaScript waits to complete
Bookmarksadd bookmarks to the PDF based on the <h1> - <h4> tags in the webpage
NoImagesdisable images
NoBackgrounddisable the background
NoInternalLinksdisable links within the domain
NoExternalLinksdisable links to external sites
NoAdsdisable ads on webpages
SetCssMediaType$typeset CSS media type to print or screen
SetTitle$titleset the title of the PDF
SetZoomFactor$factorset the zoom factor of the PDF

Functions for conversion from a URL or HTML

The PHP library lets you convert a URL to PDF or raw HTML to PDF with the functions listed below.

CreateFromURL$urlConvert a URL to PDF
CreateFromHTML$htmlConvert HTML to PDF from the string $html

Functions for saving / displaying the PDF

When the conversion is done you can choose to display the PDF to a user or save it off to a location of your choice with one of the functions below.

DisplayDisplay the PDF as attachment in the user's browser
DisplayInlineDisplay the PDF inline in the user's browser
Save$filenameSave the PDF as a local file with filename $filename
StringValueReturn the PDF as a string value

Return codes and exception handling

The PHP library throws exceptions, which you can and should check to see if the execution was succesfull or not. You can do so with the following try / catch code.

try {

   $pdf = new PDFmyURL ('yourlicensekey');
} catch (Exception $error) {

   // handle the exception, for example like this:
   echo $error->getMessage();
   echo $error->getCode();

The following is the list of codes we use.

400 Bad RequestYou didn't specify anything to convert
401 Authorization requiredYou specified an invalid license key
409 ConflictThe URL fails, usually because you used the 'block ads' setting
415 Unsupported Media TypeYou are trying to convert a document that's not HTML, such as a PDF or a Word document
429 Too Many RequestsYou have overrun a usage 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
599 Network Connect Timeout ErrorThe connection to the domain of your URL times out
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
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
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.
Detailed analysis is required of the page at hand.