• support@answerspoint.com

Convert HTML to PDF in PHP with Dompdf

Advertisement

PDF is a standard format originally created by Adobe for representing text and images in a fixed-layout document. It’s not uncommon for a web application to support downloading data, such as invoices or reports, in PDF format, so in this article we’ll go through how we can easily generate PDF documents using PHP.

Dompdf is a great library, capable of generating a PDF from HTML markup and CSS styles (it’s mostly CSS 2.1 compliant and has support for some CSS3 properties). We can decide how our content should look using these familiar technologies, and then easily convert that into a fixed document. The library has many other useful and interesting features, too.

Dompdf Installation & Setup

Download stable release of dompdf from GitHub. Extract the downloaded dompdf package and rename it with dompdf. Alternatively, you can download our source code to get all the required files together.

Instantiate Dompdf Class

To using dompdf class, you need to include the autoloader in PHP. Use the following PHP code to instantiate the dompdf class.

// Include autoloader
require_once 'dompdf/autoload.inc.php';

// Reference the Dompdf namespace
use Dompdf\Dompdf;

// Instantiate and use the dompdf class
$dompdf = new Dompdf();

 

Basic Usage

The following example shows how to use dompdf to convert to generate PDF with minimal configuration. Specify the HTML content in loadHtml() function to generate PDF and render on browser.

// Load HTML content
$dompdf->loadHtml('<h1>Welcome to Answerspoint.com</h1>');

// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');

// Render the HTML as PDF
$dompdf->render();

// Output the generated PDF to Browser
$dompdf->stream();

 

Advanced Usage

Now let’s talk about some advanced uses of Dompdf. Perhaps we want to save the generated PDF document to disk instead of sending it to the browser. Here’s how:

// Load content from html file
$html = file_get_contents("pdf-content.html");
$dompdf->loadHtml($html);

// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');

// Render the HTML as PDF
$output = $dompdf->output();
file_put_contents("/path/to/file.pdf", $output);

Instead of calling stream() like in the previous example, we use output() which returns the PDF as a string. It too accepts an optional options array, but the only option available is compress (the default is true).

  • PHP

  • asked 6 years ago
  • Gul Hafiz
    Facebook Share        
       
  • asked 6 years ago
  • viewed 3846 times
  • active 6 years ago

Top Rated Blogs