Spread the love

Dompdf package has rich features to convert html to pdf in laravel. In this article we will learn to use html to pdf using dompdf package. In most of the website there is need of to convert html to pdf or export the data in pdf format, Dompdf does this job perfectly. Dompdf has ability to convert html to pdf and also have to generate the pdf programmatically.

Laravel dompdf package PHP based style-driven library which compliant css CSS 2.1 html layout. Using this library you can import css from external or internally.

In this example we will create a simple example to export a database table in pdf format. For this we will create a database, table, model, controller and simple view for html.

Let’s understand convert html to pdf in laravel 8/ 9 with simple example

Step 1 : Install the package

I assume the you have already installed the laravel and basic connection of it like database connection and composer.

Now install the package using composer in laravel root directory, open the terminal in laravel root directory and run below command to install the dompdf package

composer require barryvdh/laravel-dompdf

Step 2 : Create a table, model and fill data

Now, for an example i am creating here a table using migration and then i am going to fill the data in it, so create model and migration

php artisan make:model Article -m

this will generate the model and migration file


namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Article extends Model
    use HasFactory;

and migration file database/migrations/timestamp_create_articles_table.php


use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateArticlesTable extends Migration
     * Run the migrations.
     * @return void
     public function up()
        Schema::create('articles', function (Blueprint $table) {

     * Reverse the migrations.
     * @return void
    public function down()

and then migrate the migration

php artisan migrate

Now create seeder in database/seeders/DatabaseSeeder.php


namespace Database\Seeders;

use Illuminate\Database\Seeder;

// Import DB and Faker services
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;

class DatabaseSeeder extends Seeder
     * Seed the application's database.
     * @return void
    public function run()
        $faker = Faker::create();

    	for ($i=0;$i<=100;$i++) {
                'title' => $faker->name,
                'body' => $faker->text,
                'email' => $faker->email,
                'updated_at' =>$faker->datetime,
                'created_at' => $faker->datetime              

Run Seeder in command line

php artisan db:seed

Step 3 : Create controller

Let’s create a controller and add a methods showArticleAndExport and also add condition for export article here

php artisan make:controller ArticleController

and add the below code


namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Article;

use PDF;

class ArticleController extends Controller {
    // Show products
    public function showArticleAndExport(Request $request){

     // added searching as well
      $product = Article::when($request->has("title"),function($q)use($request){
            return $q->where("title","like","%".$request->get("title")."%");
  // or
  //    $product = Article::all();

        $pdf = PDF::loadView('articles.article', ['articles'=>$articles]);
        return $pdf->download('articles.pdf');
       return view('articles.article',['articles'=>$articles]);


here we added showArticleAndExport method to show the list of articles as well to export the article on the condition of request params.

Step 5 : Create the views

Create a view resource/articles/article.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Readerstacks Laravel html to pdf conversion</title>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
  <link href="//netdna.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />


<body class="antialiased">
  <div class="container">
    <!-- main app container -->
    <div class="readersack">
      <div class="container">
        <div class="row">
          <div class="col-md-12 ">
            <h3>Convert html to pdf in laravel 8 / 9 - Readerstacks</h3>
            <a class='btn btn-info' href='{{url("html-to-pdf?export=1")}}'>Export PDF</a>
            <div id="search">

              <form id="searchform" name="searchform">
                <div class="form-group">
                  <label>Search by Title</label>
                  <input type="text" name="title" value="{{request()->get('title','')}}" class="form-control" />

                <div class="form-group">
                  <label>Search by body</label>
                  <input type="text" name="body" value="{{request()->get('body','')}}" class="form-control" />

                <button class='btn btn-success' >Search</button>

            <div id="pagination_data">
              <table class="table table-striped table-dark table-bordered">
                  <th>Sr No.</th>


                @foreach($articles as $article)

    <!-- credits -->
    <div class="text-center">
        <a href="#" target="_top">Laravel html to pdf conversion        </a>
        <a href="https://readerstacks.com" target="_top">readerstacks.com</a>


Step 6 : Create Routes

Last step is to create the routes to show the form and submit the form


use Illuminate\Support\Facades\Route;
use \App\Http\Controllers\ArticleController;

Route::get('/html-to-pdf',[ArticleController::class, 'showArticleAndExport']); 


Converting simple html to pdf in the fly

If you want to convert simple html to pdf then you can simply create a route and add this code

    $pdf = \App::make('dompdf.wrapper');
    return $pdf->stream();

Save to storage

you can save in to the storage of your application and later you can download it without any processing of conversion

PDF::loadHTML($html)->setPaper('a4', 'landscape')->setWarnings(false)->save('myfile.pdf')

Add page break

.page-break {
    page-break-after: always;
<h1>Page 1</h1>
<div class="page-break"></div>
<h1>Page 2</h1>

Leave a Reply