How to Convert HTML to PDF with PHP

Home / PHP / How to Convert HTML to PDF with PHP

PDF documents such as ebooks, statements, brochures, and reports often require headers, footers, and page numbers. More complex documents may need title page layouts or headers to vary from page to page. 

Fortunately, it’s easy to make these complex documents with DocRaptor’s HTML to PDF API and their PHP library. You may be familiar with some of the open-source HTML to PDF libraries, but they are almost all based on browser engines and cannot create the complex PDFs described above or even some of the basic PDF pages without hacks and polyfills.

This tutorial will walk you through DocRaptor’s simple setup and show some basic PDF conversion examples.

First, add docraptor to your Gemfile or require the docraptor gem.

Then, instantiate the agent and authenticate with your DocRaptor API key. Alternatively, you can use their YOUR_API_KEY_HERE trial key which doesn’t even require creating an account (it only works for test mode documents though):

$docraptor = new DocRaptor\DocApi();
$docraptor->getConfig()->setUsername(“YOUR_API_KEY_HERE”);

Then it’s as simple as:

$doc = new DocRaptor\Doc();
$doc->setDocumentContent(“Hello World”);
// $doc->setDocumentUrl(“http://docraptor.com/examples/invoice.html
$doc->setDocumentType(“pdf”);
// $doc->setJavascript(true);
// $prince_options = new DocRaptor\PrinceOptions();
// $doc->setPrinceOptions($prince_options);
// $prince_options->setMedia(“screen”);
// $prince_options->setBaseurl(“http://hello.com”);

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

As you can see, you can create the PDF from HTML or a URL. You can also enable JavaScript parsing, which they turn off by default to speed up PDF conversion time. In the backend, DocRaptor uses the high-end Prince conversion engine, which is why their documents are normally better and smaller than documents from the open-source tools.

The PHP library is pretty straightforward, but what I really appreciate about DocRaptor is how easy the HTML and CSS is. For example, the headers and footer code is just:

<style>

header {

  flow: static(header-html);

}

@page {

  margin-top: 80px;

  @top {

    content: flow(header-html);  

  }

}

</style>

<header>

  <a href=”https://docraptor.com”>DocRaptor is awesome!</a>

  <img src=”https://docraptor.com/docraptor-logo.png” />

</header>

<!– Note: The header content is ABOVE the rest of the document content –>

<p>Normal document content</p>

And page numbers work like:

.page-number {
content: “Page ” counter(page) ” of ” counter(pages);
}

That page number content can also be inserted into the header or footer.
There are a lot more examples and links to other agents on the DocRaptor documentation site. Give them a look!

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *