DocRaptor HTML TO PDF API

How to Convert HTML-to-PDF with PHP

The DocRaptor HTML to PDF API is the easiest way to create high-quality PDFs documents. We’ve been maintaining our PHP agent since 2015. This page will walk you through installing, setting up, and using the DocRaptor PHP library.

The biggest reason to choose DocRaptor for your PHP project is affordable and no-maintenance access to the Prince PDF conversion engine along with our professional support. The Prince engine normally costs thousands of dollars, but is irreplaceable for making complex PDFs with headers and footers, footnotes, page floats, page break rules, and more. It’s the best HTML to PDF generator and it’s easy to add to your PHP application with DocRaptor’s API.

No Signup Required

All of the below code examples can be copy and pasted or downloaded and ran AS IS. No signup is required. Our public API key (YOUR_API_KEY_HERE) is available and free for testing usage. Only test mode is supported, though, and all documents will be watermarked.

When you sign up for a free account, you can remove the watermark and access our support team. We know creating PDF documents from HTML can sometimes be tricky and our team has years of experience helping developers. Paid plans start at just $15/month.

Package Installation

To get started, just add the DocRaptor agent via composer:

composer require docraptor/docraptor

Hello World! Example

The most basic example of the DocRaptor PHP agent is:

docraptor-hello.php
Download
<?php

require_once __DIR__ . "/vendor/autoload.php";

$docraptor = new DocRaptor\DocApi();
# this key works in test mode!
$docraptor->getConfig()->setUsername("YOUR_API_KEY_HERE");

try {
    $doc = new DocRaptor\Doc();
    $doc->setTest(true); # test documents are free but watermarked
    $doc->setDocumentType("pdf");
    $doc->setDocumentContent("<html><body>Hello World!</body></html>");
    # $doc->setDocumentUrl("https://docraptor.com/examples/invoice.html");
    # $doc->setJavascript(true);
    # $prince_options = new DocRaptor\PrinceOptions();
    # $doc->setPrinceOptions($prince_options);
    # $prince_options->setMedia("print"); # @media 'screen' or 'print' CSS
    # $prince_options->setBaseurl("https://yoursite.com"); # the base URL for any relative URLs

    $response = $docraptor->createDoc($doc);

    # createDoc() returns a binary string
    file_put_contents("docraptor-hello.pdf", $response);
    echo "Successfully created docraptor-hello.pdf!";
} catch (DocRaptor\ApiException $error) {
    echo $error . "\n";
    echo $error->getMessage() . "\n";
    echo $error->getCode() . "\n";
    echo $error->getResponseBody() . "\n";
}

To generate the PDF, download or copy the above PHP code and run this in your console:

php docraptor-hello.php

Advanced HTML Example

Let’s move on from the basics and get fancy with a repeating header, table of content with leaders, a title page without a header, and some footnotes. Here’s the HTML and CSS:

docraptor-advanced-content.html
Download
<html>
  <head>
    <style>
      /* Create a running element */
      #header-and-footer {
        position: running(header-and-footer);
        text-align: right;
      }

      /* Add that running element to the top and bottom of every page */
      @page {
        @top {
          content: element(header-and-footer);
        }
        @bottom {
          content: element(header-and-footer);
        }
      }

      /* Add a page number */
      #page-number {
        content: "Page " counter(page);
      }

      /* Create a title page with a full-bleed background and no header */
      #title-page {
        page: title-page;
      }

      @page title-page {
        background: url('https://docraptor-production-cdn.s3.amazonaws.com/tutorials/raptor.svg') 50% 50px / 80% no-repeat #DDE4F3;
        @top {
          content: "";
        }
      }

      #title-page h1 {
        padding: 500px 0 40px 0;
        font-size: 75px;
      }

      /* Dynamically create a table of contents with leaders */
      #table-of-contents a {
        content: target-content(attr(href)) leader('.') target-counter(attr(href), page);
        color: #135697;
        text-decoration: none;
        display: block;
        padding-top: 5px;
      }

      /* Float the footnote to a footnotes area on the page */
      .footnote {
        float: footnote;
        font-size: small;
      }

      .page {
        page-break-after: always;
      }

      body {
        counter-reset: chapter;
        font-family: 'Open Sans';
        color: #135697;
      }
    </style>
    <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;800&display=swap" rel="stylesheet">
  </head>
  <body>
    <div id="title-page" class="page">
      <h1>The Official DocRaptor eBook</h1>
      <div id="table-of-contents">
        <a href="#chapter-1"></a>
        <a href="#chapter-2"></a>
        <a href="#chapter-3"></a>
      </div>
      <div id="header-and-footer">
        <span id="page-number"></span> | The Official DocRaptor eBook
      </div>
    </div>
    <div class="page">
      <h2 id="chapter-1">What is DocRaptor?</h2>
      <p>DocRaptor is an HTML to PDF API!</p>
    </div>
    <div class="page">
      <h2 id="chapter-2">Why should I use DocRaptor?</h2>
      <p>It's super easy and also has the most powerful conversion capabilities!</p>
    </div>
    <div class="page">
      <h2 id="chapter-3">How much does it cost?</h2>
      <p>
        We have a free plan!<span class="footnote">Includes five documents a month</span>
      </p>
    </div>
  </body>
</html>

The PHP code is mostly the same as the previous example, except we’ll read the external HTML file and then make the PDF:

docraptor-advanced.php
Download
<?php

require_once __DIR__ . "/vendor/autoload.php";

$docraptor = new DocRaptor\DocApi();
# this key works in test mode!
$docraptor->getConfig()->setUsername("YOUR_API_KEY_HERE");

try {
    $doc = new DocRaptor\Doc();
    $doc->setTest(true); # test documents are free but watermarked
    $doc->setDocumentType("pdf");
    $doc->setDocumentContent(file_get_contents("docraptor-advanced-content.html"));
    # $doc->setDocumentUrl("https://docraptor.com/examples/invoice.html");
    # $doc->setJavascript(true);
    # $prince_options = new DocRaptor\PrinceOptions();
    # $doc->setPrinceOptions($prince_options);
    # $prince_options->setMedia("print"); # @media 'screen' or 'print' CSS
    # $prince_options->setBaseurl("https://yoursite.com"); # the base URL for any relative URLs

    $response = $docraptor->createDoc($doc);

    # createDoc() returns a binary string
    file_put_contents("docraptor-advanced.pdf", $response);
    echo "Successfully created docraptor-advanced.pdf!";
} catch (DocRaptor\ApiException $error) {
    echo $error . "\n";
    echo $error->getMessage() . "\n";
    echo $error->getCode() . "\n";
    echo $error->getResponseBody() . "\n";
}

To make the PDF, download or copy the above sample and then run:

python docraptor-advanced.php

Important API Parameters

Most of our DocRaptor and Prince’s functionality is managed directly in your HTML document with CSS, but there are a few important API parameters you should know. These are defined via the PHP agent. These are just the most common parameters; you can see the full list on our API documentation page.

test

All the code examples on this page have the test parameter enabled. This allows you to use our public, testing API key. However, test documents always have watermarks so you’ll obviously want to set test to false when you’ve completed your document development and are ready to make non-watermarked documents.

javascript

JavaScript is disabled by default. This ensures documents are converted as quickly as possible. You can enable JavaScript execution by setting the parameter to true.

It's ocassionally difficult to detected when JavaScript has or has not completed its execution, especially when rendering graphs or loading external data. In these situations, rendering can by delayed until you explictly tell DocRaptor to render the document.

You may also use Prince’s own JavaScript engine. We’ve found our standard JavaScript engine to be better in most cases, but Prince’s engine supports some advanced, PDF-specific functionality such as multi-rendering passes and interacting with the PDF "DOM".

async

The majority of our documents are generated synchronously. However, synchronous documents are limited to a maximum of 60 seconds of generation time. If your document is large or contains lots of external assets, you can switch to asynchronous generation. Asynchronous documents have a 10 minute time limit.

There’s no difference in pricing, just a different method call and interaction style. You can either supply a callback URL to be notified when your document has been completed or ping us for a status check. Either way, we’ll provide a URL where your document can be retrieved.

It’s important to note that the PHP agent calls a different method (createAsyncDoc) when generating a document asynchronously:

docraptor-async.php
Download
<?php

require_once __DIR__ . "/vendor/autoload.php";

$docraptor = new DocRaptor\DocApi();
# this key works in test mode!
$docraptor->getConfig()->setUsername("YOUR_API_KEY_HERE");

try {
    $doc = new DocRaptor\Doc();
    $doc->setTest(true); # test documents are free but watermarked
    $doc->setDocumentType("pdf");
    $doc->setDocumentContent("<html><body>Hello World!</body></html>");
    # $doc->setDocumentUrl("https://docraptor.com/examples/invoice.html");
    # $doc->setJavascript(true);
    # $prince_options = new DocRaptor\PrinceOptions();
    # $doc->setPrinceOptions($prince_options);
    # $prince_options->setMedia("print"); # @media 'screen' or 'print' CSS
    # $prince_options->setBaseurl("https://yoursite.com"); # the base URL for any relative URLs

    # different method than the synchronous documents
    $response = $docraptor->createAsyncDoc($doc);

    $done = false;
    while (!$done) {
        $status_response = $docraptor->getAsyncDocStatus($response->getStatusId());
        echo "doc status: " . $status_response->getStatus() . "\n";
        switch ($status_response->getStatus()) {
            case "completed":
                $pdf = $docraptor->getAsyncDoc($status_response->getDownloadId());
                # getAsyncDoc() returns a binary string
                file_put_contents("docraptor-async.pdf", $pdf);
                echo "Wrote PDF to docraptor-async.pdf\n";
                $done = true;
                break;
            case "failed":
                echo "FAILED\n";
                echo $status_response;
                $done = true;
                break;
            default:
                sleep(1);
        }
    }
} catch (DocRaptor\ApiException $error) {
    echo $error . "\n";
    echo $error->getMessage() . "\n";
    echo $error->getCode() . "\n";
    echo $error->getResponseBody() . "\n";
}

hosted

Sometimes, you just need a URL to use, not a binary document. For those cases, our hosted document add-on makes it easy. We’ll temporarily or permanently host your document on a non-branded URL. You can expire hosted documents manually, programmatically, or by defining time or download limits.

To generate a hosted document using the PHP agent, use the createHostedDoc or createHostedAsyncDoc methods:
docraptor-hosted.php
Download
<?php

require_once __DIR__ . "/vendor/autoload.php";

$docraptor = new DocRaptor\DocApi();
# this key works in test mode!
$docraptor->getConfig()->setUsername("YOUR_API_KEY_HERE");

try {
    $doc = new DocRaptor\Doc();
    $doc->setTest(true); # test documents are free but watermarked
    $doc->setDocumentType("pdf");
    $doc->setDocumentContent("<html><body>Hello World!</body></html>");
    # $doc->setDocumentUrl("https://docraptor.com/examples/invoice.html");
    # $doc->setJavascript(true);
    # $prince_options = new DocRaptor\PrinceOptions();
    # $doc->setPrinceOptions($prince_options);
    # $prince_options->setMedia("print"); # @media 'screen' or 'print' CSS
    # $prince_options->setBaseurl("https://yoursite.com"); # the base URL for any relative URLs

    # different method than the non-hosted documents
    $response = $docraptor->createHostedDoc($doc);

    echo "The PDF is hosted at " . $response->getDownloadUrl() . "\n";
} catch (DocRaptor\ApiException $error) {
    echo $error . "\n";
    echo $error->getMessage() . "\n";
    echo $error->getCode() . "\n";
    echo $error->getResponseBody() . "\n";
}

Advanced HTML & CSS for PDF Creation

The majority of DocRaptor’s powerful features are defined with HTML and CSS within your document. Much of it is standard (though not always well-supported in the browser) CSS. In some cases, however, Prince has created powerful, custom CSS rules.

The most common HTML and CSS uses include:

For complete documentation, visit our reference library. All of these examples can be used with the PHP agent.

Other Resources & Documentation

Our full documentation site includes tutorials (with PHP example code) and troubleshooting tips, as well as account and billing and security and privacy information.

Our sample page contains particularly complex documents, all of which are fully documented within the HTML. If you want to see how a particular functionality is achieved, or merely what is possible with DocRaptor, the samples page can be very helpful.

If you’re still evaluating whether or not DocRaptor is right for your project, we’ve written a comparison of DocRaptor vs open-source projects (including some PHP options) and on online HTML to PDF APIs in general.

Finally, if you have any remaining questions or need any assistance, please contact support@docraptor.com and we’d be happy to assist further. You can also ask for help on specific conversions with document-level help requests.

Ready to get started? Try DocRaptor for free with unlimited test documents.