HTML to PDF conversion with our SDK in PHP

We offer both a ‘HTML to PDF API’ as well as this advanced SDK for HTML to PDF conversion. The HTML to PDF SDK offers even more power than the API. In fact – you’ll get usage of the API as a complementary service!

Some of the use cases for our HTML to PDF SDK are (on top of the ones for the API):

  • You want to a lot of PDF functions pre-coded for you.
  • You want to generate PDFs from raw HTML.
  • You want to generate PDFs from files that you have on your local system.
  • You want to be able to overwrite all settings that you can set in the members area with each conversion.
  • You want to generate PDF forms like proposals / invoices / timesheets etc, and you want us to design them.
  • You want to create PDFs from different sources and merge them together or use the merge functionality to have pages of different sizes and layouts into one PDF New!

When you sign up for a HTML to PDF SDK plan you get a whole bunch of goodies. You’ll get much more power and flexibility in the way you can convert to PDF.

Features additional to the HTML to PDF API

With the SDK you are able to:

  • Take advantage of the HTML to PDF API as complementary service
  • Set defaults in your members area just as with other plans
  • Override all conversion settings for each separate conversion
  • Convert from different sources like URLs, raw HTML, HTML files, but also custom forms
  • Merge different PDFs that we created for you together into one file so you can have different page layouts and other settings in one file New!
  • Use PDF encryption and protection options like print protection, copy protection and setting a ‘document open’ password
  • Use your own image or text watermark and have full control over it
  • Use your own images as ‘stationary’ or page background so you generate professional invoices, quotes and reports! New!
  • Be prepared for and request new features on top of the current ones

Requirements

Currently the HTML to PDF SDK is only available in PHP. In order to use it you need to:

  1. Have cURL on your system (see PHP.net) – don’t worry, this is usually the case!
  2. Download the PHP library

The package with the library also contains examples for you to get started. Here’s an example of what you can do with the SDK to get you started.

require 'htm2pdfapi.php';

$pdf = new Htm2PdfApi ($userid, $apikey);      // initialize, make sure you replace $userid & $apikey with your credentials

$pdf->SetPageSize('Letter');                   // this PDF will have page size 'Letter'
$pdf->SetPageOrientation('Portrait');          // and we'll use set the orientation to 'Portrait' on this one

$pdf->ConvertFromURL('http://www.google.com'); // we're going to make a PDF of http://www.google.com
$pdf->Display();                               // now lets display it to the user as attachment

Please see the examples below for more things that you can do with this awesome SDK!

The most elementary of all situations is where you’d like to take a URL and convert it into PDF. The URL can be on your own site or someone else’s site.

It takes only a few simple statements to do this:

$pdf = new Htm2PdfApi ($userid, $apikey);        // initialize, make sure you replace $userid & $apikey with your credentials
$pdf->CreateFromURL('http://www.google.com');    // convert from URL to PDF
$pdf->Display();                                 // display it to the user as attachment

Please let us know if you think there’s information missing or you just have a great example to share.

If you’d like to take raw HTML convert it into PDF then it takes only a few simple statements to do so.

In this example we’ll show you how to convert the HTML and then show it to the user inline in the browser.

You use the following statements to do this:

$pdf = new Htm2PdfApi ($userid, $apikey);        // initialize, make sure you replace $userid & $apikey with your credentials
$pdf->CreateFromHTML('....');                    // convert the string with HTML code to PDF
$pdf->DisplayInline();                           // display it to the user inline in the browser

Please let us know if you think there’s information missing or you just have a great example to share.

If you’d like to take a HTML file on your system and convert it into PDF then it takes only a few statements to do so.

In this example we’ll show you how to do just that and then save the resulting PDF on your system.

You use the following statements to do this:

$pdf = new Htm2PdfApi ($userid, $apikey);       // initialize, make sure you replace $userid & $apikey with your credentials
$pdf->CreateFromFile('/files/file.htm');        // converts this file - make sure to write the full path!
$pdf->Save('/files/yourfile.pdf');              // save the result on your system

Please let us know if you think there’s information missing or you just have a great example to share.

You can ask us to create custom forms for you. In that case we host the form for you and we allow you to call it using the SDK with a set of parameters that we agree upon.

This takes away the hassle of creating your own forms and maintaining them. It’s quite a lot of work and for us it’s easier to do, since we do it all the time. Of course this is a priced service, available upon request.

Once you have certain forms setup on our system, you can create custom defaults in your members area for each of them. In your code it becomes very simple to use them. You just define the parameters and then call our function to render the form as PDF.

$pdf = new Htm2PdfApi ($userid, $apikey);    // initialize, make sure you replace $userid & $apikey with your credentials

$pdf->CreateFromForm(1, $params);            // converts form 1 and fills it with the values from $params
$pdf->Save('/files/yourfile.pdf');           // save the result on your system
$pdf->Display();                             // display it to the user as attachment

Please let us know if you think there’s information missing or if you want to discuss this option for your business.

In some situations you’d like to encrypt and/or password protect your generated PDF. This may be to prevent certain actions to take place on the PDF (you don’t want people to copy things from the PDF or you don’t want search engines to index the content of your PDF) or you just want to allow access only to certain people. We allow you to do these things by using a few very simple functions.

Here’s an example that illustrates how you can encrypt your document, password protect it AND restrict the rights on the PDF:

$pdf = new Htm2PdfApi ($userid, $apikey);        // initialize, make sure you replace $userid & $apikey with your credentials

$pdf->SetEncryptionLevel(128,true);              // encrypt this PDF with 128 bit AES encryption
$pdf->SetPasswords('owner1','user1');            // the owner password 'owner1' allows you to change options later
                                                 // the password 'user1' can be used by users to open the document
$pdf->SetPermissions(true,true,false,true,true); // Allow everything except content copying on this PDF

$pdf->CreateFromURL('http://www.google.com');    // do the conversion
$pdf->Display();                                 // display it to the user as attachment

Please let us know if you think there’s information missing or you just have a great example to share.

In some situations you’d like to put a watermark or a stamp on your generated PDF. We actually have both these things in the same function as we feel the difference only lies in the level of opacity you indicate. We allow you to watermark or stamp your PDF with a few very simple functions.

Here’s an example that illustrates how you can watermark a PDF:

$pdf = new Htm2PdfApi ($userid, $apikey);          // initialize, replace $userid & $apikey with your credentials

$pdf->SetWatermarkLocation(100,100);               // we will put this watermark at position 100,100
$pdf->SetWatermarkTransformation(45,1);            // it's at an angle of 45 degrees and fully opague (so stamped)
                                                   // use e.g. (45,0.5) for a semi-transparant watermark
$pdf->SetWatermarkText('DRAFT','Courier','#000000', 64); // Print DRAFT in Courier, color black, size 64

$pdf->CreateFromURL('http://www.google.com');      // do the conversion
$pdf->Display();                                   // display it to the user as attachment

Please let us know if you think there’s information missing or you just have a great example to share.

There are quite some situations, where you’d like to use your company’s stationary as the background for the PDFs you generate. We have some very easy-to-use functions that will help you do that.

The stationary images that you use will be used as the background for the PDF pages and you can decided if you want to use a different image for the first page, last page and/or the pages in between. All content will be then converted on top of the stationary. Note that this means that non-transparent images or background-color CSS will also be displayed OVER the stationary.

Here’s an example that illustrates how you can use stationary for your PDF. In this case we assume that you want to have an image for the first page and one for all other pages and that you’d like to stretch those images all over the page.

$pdf = new Htm2PdfApi ($userid, $apikey);   // initialize, replace $userid & $apikey with your credentials

$pdf->SetStationaryTransformation(0,1,0,0);      // angle=0, opacity=fully opague and horizontal and vertical scaling to fit the page (the value 0 represents fitting to the page width or height)
$pdf->SetStationaryImages('http://yoursite.com/img1.png', 'http://yoursite.com/img2.png');
                                                 // use img1.png as stationary for the first page
                                                 // use img2.png as stationary for all subsequent pages

$pdf->CreateFromURL('http://www.google.com');      // do the conversion
$pdf->Display();                                   // display it to the user as attachment

Please let us know if you think there’s information missing or you just have a great example to share.

With the HTML to PDF SDK you are able to override the default conversion settings for each PDF that you create.

The nice thing about this is, that you only have to do this for the settings that you want to override. The rest of the settings will be taken from the ones you define in your members area.

Below we will show you examples for the settings you can override.

require 'htm2pdfapi.php';

$pdf = new Htm2PdfApi ($userid, $apikey);  // initialize, make sure you replace $userid & $apikey with your credentials

$pdf->SetPageSize('Letter');	           // if you want to change the page size to 'Letter'
$pdf->SetPageDimensions(300,0,'mm');       // if you want to set an exact width & height (this is for a single page PDF with width 300mm)
$pdf->SetPageOrientation('Portrait');      // if you want to change the orientation to 'Portrait'
$pdf->SetMargins(5,5,5,5,'mm');            // if you want to change the margins to 5 millimeters on all sides (use pt for points and in for inches)
$pdf->SetGrayscale('on');                  // if you want to enable grayscale (disable = 'off')
$pdf->SetJavaScript('off');                // if you want to disable JavaScript (enable = 'on')
$pdf->SetJavaScriptDelay(300);             // if you want to wait 300ms for JavaScript to complete
$pdf->SetImages('on');                     // if you want to render the PDF with images (disable = 'off')
$pdf->SetBackground('off');                // if you want to render the PDF without the background (enable = 'on')
$pdf->SetCssMediaType('print');            // if you want to use the ("print") instead of the default ("screen") CSS media type

$pdf->SetHeader('<html>...</html>');       // if you want to set a custom header in HTML
$pdf->SetFooter('<html>...</html>');       // if you want to set a custom footer in HTML
$pdf->SetPageOffset(1);                    // if you want to add a number (here: 1) to the page numbering of header/footer

$pdf->SetEncryptionLevel(128, false);       // if you want to encrypt the document with 128 RC4 encryption
$pdf->SetPasswords('master', 'user');       // if you want to set the owner password to 'master' and the document open password to 'user'
$pdf->SetPermissions(false, false, false, false, false); // if you want to disallow all permissions

$pdf->SetWatermarkLocation(100,100);           // If you want to put your watermark at position (100,100)
$pdf->SetWatermarkTransformation(45,1,2,2);    // If you want to rotate the watermark 45 degrees, make it fully opague (like a stamp) and twice as big
$pdf->SetWatermarkImage('http://www.htm2pdf.co.uk/img/logo.png'); // If you want to use our logo as watermark
$pdf->SetWatermarkText('DRAFT','Tahoma','#FF0000', 64); // If you want to watermark 'DRAFT' in Tahoma font, size 64 and color red

$pdf->SetStationaryLocation(100,100);          // If you want to put your stationary/background image(s) at position (100,100)
$pdf->SetStationaryTransformation(0,1,0,0);    // If you want make it fully opague and stretch it over full background horizontally and vertically
$pdf->SetStationaryImages('http://www.htm2pdf.co.uk/img/logo.png');    // If you want to use our logo as the background stationary for the first page, and also for the next pages and the last page, since you didn't specify those in this example

$pdf->SetHttpAuthentication('user','pass');    // If you want to authorize our client with HTTP Authentication user name 'user' and password 'pass'

Please let us know if you think there’s information missing or if you have suggestions to improve this section.

The SDK allows you to create PDFs from multiple sources and with different options, by allowing you to merge the PDFs that we have in our cache.

This allows you to create PDFs with a huge amount of freedom and flexibility. You can basicly create every single page as a single PDF and then in the end merge them alltogether into one PDF. You just have to indicate how many we have to take from our cache. If you don’t specify any pages, we will just put them all into one big PDF one page after the other. If you do want to be more selective, you just select which pages you want and we’ll take care of that for you.

Example – merging PDFs from two different URLs

Suppose you want to merge the homepage of Google and the one from the BBC into one PDF. Without merging you wouldn’t be able to do this. But with merging it becomes very simple. You just convert both the URLs as you would normally do with the SDK (you can even use these PDFs in the process) and then you merge them together and get the end result.

require 'htm2pdfapi.php';

$pdf = new Htm2PdfApi ($userid, $apikey);         // initialize, make sure you replace $userid & $apikey with your credentials

$pdf->SetPageSize('Letter');
$pdf->SetPageOrientation('Portrait');
$pdf->CreateFromURL('http://www.google.com');     // after this you have a PDF of google.com in our cache in Portrait
//$pdf->Save('...');                              // you can save it if you want

$pdf->SetPageOrientation('Landscape');
$pdf->CreateFromURL('http://www.bbc.co.uk');      // after this you have a PDF of bbc.co.uk in our cache in Landscape

$pdf->MergeFromCache(2);                          // now we'll merge the 2 last PDFs for you

$pdf->Display();                                  // the PDF shows Google first and then the pages of the BBC website

Example – specifying specific pages to merge

The previous example showed how you can use the MergeFromCache function to easily merge PDFs together. In the most common situations you’ll probably just use it to merge the last x PDFs together, cause you’ll already know what your final PDF should look like and you use HTML to do the rest.

But in some cases you may want to have more control over the pages you select from each PDF that you merge. Or you may want to skip one of the last ones alltogether. In that case the 2nd parameter of the MergeFromCache function comes in handy.

The 2nd parameter that you can optionally pass to the MergeFromCache function is an array, that indicates for each PDF which pages you want to take. It should follow the following rules:

  • contain the same amount of entries as the amount of PDFs you want to merge, so if you merge two PDFs you need two entries in array $pages
  • each entry of the $pages array can only contain pages or page ranges and use the following characters: digits, commas (,), hyphens (-) and the ‘z’ character, which indicates the last page
  • each page can only be used per PDF and each page should exist in the PDF
  • if you want to skip a PDF from merging alltogether then you should use a 0 as the only entry for that PDF in the $pages array

Let’s look at some examples, so you can use it more easily.


$pdf->MergeFromCache(3);                 // the 3 last PDFs fully
$pdf->MergeFromCache(2,('1','2'));       // the 1st page of the 1st PDF and the 2nd of the 2nd PDF
$pdf->MergeFromCache(2,('1-z','z-1'));   // all pages of the 1st PDF and the all pages in reverse order of the 2nd PDF
$pdf->MergeFromCache(3,('1-z',0,'2,4')); // all pages of the 1st PDF, skip the 2nd PDF, and merge pages 2 and 4 of the 3rd PDF

Please let us know if you think there’s information missing or if you have suggestions to improve this section.

Our advanced SDK consists of a set of easy to use functions, which you can use to control the PDF conversion process.
We’re still expanding this list at the time of writing and will keep on adding new features in the near and far future.

Before you call any of these functions you need to declare an object of the class Htm2PdfAPI. You include this class at the top of your PHP script, by including our SDK library.

require 'htm2pdfapi.php';

$pdf = new Htm2PdfApi($userid, $apikey); // replace $userid and $apikey with your own data

After these statements you can begin using our functions. You would do this in the following sequence:

  1. Use functions to update the conversion settings (optional)
  2. Use one of the four conversion functions to convert something to PDF
  3. Use one or more functions to display and/or save the resulting PDF

We’ve listed all functions and their explanation below.

SDK functions – general settings

NameDescription
SetServerChoose the shared service closest to you or choose your dedicated/unmetered server.
Shared servers can be ‘europe’, ‘usa’ or ‘asia’.
SetCurlTimeOutSets the default time that your Curl waits for a response. We default this to 10 seconds. Override if you’re on a low speed network or are converting huge files.

SDK functions – setting options

Note that you only need to set options if you want to override options as stored in your members area.

NameDescription
SetPageSizeSet your page size to one of the allowed values like A4, Letter etc.
SetPageDimensionsSet your page size to exact width & height. Set height to 0 to generate a single page PDF where the height is automaticly determined.
SetPageOrientationSet your page orientation to ‘Landscape’ or ‘Portrait’
SetMarginsSet your top, bottom, left and right margins in inches, points or millimeters
SetGrayscaleRender the PDF in Grayscale (“on”) or not (“off”)
SetJavaScriptRender the PDF with JavaScript “on” or “off”
SetJavaScriptDelaySet the time in msec that our renderer waits for JavaScript
SetImagesRender the PDF with images (“on”) or without (“off”)
SetBackgroundRender the PDF with background (“on”) or without (“off”)
SetCssMediaType New!Set the CSS media type to “print” or the default “screen”

SDK functions – encryption and password protection

These functions can be used to generate an encrypted PDF with or without a ‘document open password’. They allow you to prevent users from doing certain things with a PDF as well as search engines reading the content of the PDF.

NameDescription
SetEncryptionLevelSet the desired level of encryption for the PDF. Possible options are:

  • 40 for 40-bit RC4 encryption.
  • 128 for 128-bit RC4 encryption, requires Acrobat reader 5 or later
  • 128 with aes=true – for 128-bit AES encryption, requires Acrobat reader 7 or later
  • 256 for 256-bit AES encryption, requires Acrobat reader X or later
SetPasswordsSet your owner password, which is needed to edit encryption and rights protection settings, and your user or ‘document open’ password. If not specified we’ll default these to not needed.
SetPermissionsSet permissions for printing, document modification, content copying, annotation and accessibility for visually impaired people.

SDK functions – watermarking

You can use the following functions to get a watermark on each of the pages of your PDF. You can use either an image or a text as watermark. Some services out there distinguish watermarking from stamping, but in our opinion they’re both the same and only the level of opacity you set differentiates between the two. If you use an opacity of 1 you will see the watermarked ‘stamped’ over your content.

NameDescription
SetWatermarkLocationIndicate where the watermark should start.
Note that the top left of the image will start at this location, whilst this location will indicate the BOTTOM left of a text watermark
SetWatermarkTransformationIndicate the rotation, opacity and scaling (horizontal and vertical) of the watermark
SetWatermarkImageAdds an image as watermark to all the pages of your PDF
SetWatermarkTextAdds a text watermark to all the pages of your PDF
You control font, size and color

SDK functions – stationary aka page background

If you want to use your own ‘stationary’ or background to the content that you convert, then the stationary functions will come in handy. They allow you to choose any image you like and use it as the page background for your pages. Please note that any content that you convert will go OVER this stationary image, so if you use non-transparent images or background-color or something else – the stationary image of course will be behind that and not be visible.

NameDescription
SetStationaryLocationIndicate where the stationary should start.
Position 0,0 is the top left of the page. This means stationary will be behind your margins as well if you want.
SetStationaryTransformationIndicate the rotation, opacity and scaling (horizontal and vertical) of the watermark
If you set scaling to 0, we will automatically stretch the image over the full width (in case horizontal scaling is 0) and/or height (in case vertical scaling is 0)
SetStationaryImagesAllows you to set the image for the stationary of the first page, the next pages (so not first and not last) and the last page of your PDF
This allows you to have a different ‘cover letter’ stationary then your content pages

SDK functions – authorization

If you have content on your website, which is behind authorization protocols, we can only access it if you supply us with the authorization details. Otherwise you’d have to resort to creating ‘temporary pages’ or to pass the content as HTML to our SDK. By default we offer access over basic HTTP authentication via the below function. If you want us to use other methods, then please contact us to receive a quote for custom work.

NameDescription
SetHttpAuthenticationSets the user name and password for our renderer to use when we access your site with basic HTTP authentication

SDK functions – conversion

NameDescription
ConvertFromURLConverts a valid URL to a PDF file
ConvertFromHTMLConverts the raw HTML to a PDF file
ConvertFromFileConverts a file that’s passed to a PDF file
ConvertFromFormConverts a custom form with certain parameters to a PDF file
Only available if we have built/uploaded one or more forms for you

SDK function – merging

NameDescription
MergeFromCacheMerges pages from different PDFs in our cache together into one
You can select pages as you please and reorganize as well as long as the PDFs are still in our cache.
Currently we cache the PDFs we created for 2 hours. Merged PDFs are NOT cached.

SDK functions – displaying/saving the PDF result

NameDescription
DisplayDisplays a PDF as attachment to the user
You can pass your own filename if you want
DisplayInlineDisplays a PDF inline in the user’s browser
SaveSave a PDF on your system

Please let us know if you think there’s information missing or if you have suggestions to improve this section.

We strongly advise you to use our functions in a so-called ‘try / catch’ block. In that way you can handle exceptions properly as there are situations, where errors occur.

In order to catch exceptions your code should look something like this:

Try {
   $pdf = new Htm2PdfApi ($userid, $apikey);
   $pdf->CreateFromURL('http://www.google.com');
   $pdf->Display();
} catch Exception($error) {
   // do something with $error->getMessage() and/or $error->getCode()
}

Almost all of the exceptions you will catch are client-side errors. It means something went wrong, because of the way the SDK was called. It could be there are pieces of configuration missing on your system or data was passed incorrectly.

We’ve listed the error codes and their explanation below.

Server side errors

CodeDescriptionCause and remarks
400Bad RequestThere’s either a problem with the source of the SDK (did you modify it?) or you have used the SDK without credentials or the wrong parameters. If you’re using cURL on the command line you’ve most likely used the wrong parameters.
401Authorization RequiredThe credentials you supplied are not correct, please verify your User ID and API key.

Client side errors

CodeDescriptionCause and remarks
8xxcURL 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.
If you’re suffering from timeouts due to high latency on your network, you can use SetCurlTimeOut() to increase the transfer time.
900URL is invalidYou should pass a valid URL. URLs can start with http:// or https:// or have no prefix like www.google.com.
901HTML string can not be emptyYou must pass HTML code. Therefore do not try to pass an empty string.
905Watermark 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.
906Watermark 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.
907Stationary 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.
910Filename 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.
911File can not be emptyThe file you’re trying to send does not contain any data.
920Not possible to save PDF fileYou’re most likely out of space on your system and are not able to save the file locally.
930cURL is not installedYou need cURL on your system to be able to work with the PHP SDK. Please follow the installation instructions from PHP.net.
940Access error – your system’s web user can not write toBy 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($tmp) to change the directory we need to use.
950Not enough files to mergeYou indicated more files to merge than our left in our cache
951Merge parameters incorrectPlease check your merge parameters. You need to specify at least one file and if you specified pages, then they need to be specified correctly and for all files.
952Files could not be mergedMost likely you made an error in the specification of the pages you wanted to merge, e.g. a page that doesn’t exist or the same page twice.
990We 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.

Please let us know if you think there’s information missing or if you have suggestions to improve this section.

We have subscriptions for any number of sites and for low and high-traffic sites. If you want to try our service, Sign up!


Start right now! Sign up →