Convert HTML to PDF in Laravel with Dompdf

PDF is a commonly used format to store data in a file for offline uses. If you want to allow the user to download HTML content in a PDF file, HTML to PDF conversion functionality needs to be implemented in the web application. The Dompdf library can be used to convert HTML to PDF using PHP.

The Dompdf is a PHP library that helps to convert HTML to PDF document. If your application is built with Laravel, the Dompdf library is the best option to create a PDF file and add HTML content to PDF document. In this tutorial, we will show you how to convert HTML to PDF in Laravel with Dompdf.

Convert HTML to PDF in Laravel

Run the following command to install Dompdf via Composer in your Laravel application.

composer require dompdf/dompdf

For this example, we will use the convert() method of the HomeController to convert HTML content to PDF document.

  • At first, define the reference the Dompdf namespace.
  • In the convert() method, add the code to handle the HTML to PDF conversion process.
<?php 

namespace App\Http\Controllers;

use 
App\Http\Controllers\Controller;

// Reference the Dompdf namespace
use Dompdf\Dompdf;

class 
HomeController extends Controller
{
    
    public function 
convert()
    {
        
// Instantiate and use the dompdf class
        
$dompdf = new Dompdf();
        
        
// Load HTML content 
        
$dompdf->loadHtml('<h1>Welcome to CodexWorld.com</h1>'); 
         
        
// (Optional) Setup the paper size and orientation 
        
$dompdf->setPaper('A4''landscape'); 
         
        
// Render the HTML as PDF 
        
$dompdf->render();
        
        
// Output the generated PDF (1 = download and 0 = preview)
        
$dompdf->stream("welcome.pdf", array("Attachment"=>1));
    }
    
}

Conclusion

This HTML to PDF converter script provides a simple way to create a PDF document with dynamic content in Laravel 8. You can use this example code in any version of Laravel Framework as well as Lumen. There are various configurations are available in Dompdf to customize the PDF creation functionality as per your needs.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

Leave a reply

keyboard_double_arrow_up