24

Convert HTML to PDF in Laravel with Dompdf

 3 years ago
source link: https://www.codexworld.com/convert-html-to-pdf-in-laravel-with-dompdf/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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.

Are you want to get implementation help, or modify or enhance the functionality of this script? Submit Paid Service Request

If you have any questions about this script, submit it to our QA community - Ask Question


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK