To page break in PDF using DomPDF Laravel, you can use the following steps:
- Install the DomPDF package:
composer require barryvdh/laravel-dompdf
- Add the following line to your
config/app.php
file:
PHP
'providers' => [
...
Barryvdh\DomPDF\ServiceProvider::class,
],
- Publish the DomPDF configuration file:
php artisan vendor:publish --provider="Barryvdh\DomPDF\ServiceProvider"
- Create a new PDF class:
PHP
namespace App\Exports;
use Barryvdh\DomPDF\PDF;
class PdfExport extends PDF
{
/**
* Load the HTML template.
*
* @return $this
*/
public function loadHTML()
{
$html = view('pdf.template', [
'data' => $this->data,
]);
$this->setHtml($html);
return $this;
}
/**
* Generate the PDF.
*
* @return mixed
*/
public function generate()
{
$this->loadHTML();
return $this->output();
}
}
- Create a new controller that will export the PDF:
PHP
namespace App\Http\Controllers;
use App\Exports\PdfExport;
class PdfController extends Controller
{
/**
* Export the PDF.
*
* @return mixed
*/
public function export()
{
$pdf = new PdfExport();
$pdf->data = [
// Your data here
];
return $pdf->generate();
}
}
- Add the following route to your
routes/web.php
file:
PHP
Route::get('/pdf/export', [PdfController::class, 'export']);
- Visit the
/pdf/export
route in your browser to download the PDF.
Page Break
To add a page break to your PDF, you can use the following HTML:
HTML
<div style="page-break-before: always;"></div>
For example, you can add the following code to your PDF template to add a page break after the first section:
HTML
<h1>Section 1</h1>
<div style="page-break-before: always;"></div>
<h1>Section 2</h1>
This will generate a PDF with two pages, with the first page containing the “Section 1” heading and the second page containing the “Section 2” heading.
You can also add a page break after each element in a list. To do this, you can use the following code:
HTML
<ul>
<li>Item 1</li>
<div style="page-break-before: always;"></div>
<li>Item 2</li>
<div style="page-break-before: always;"></div>
<li>Item 3</li>
</ul>
This will generate a PDF with three pages, with each page containing a single item from the list.
Conclusion
Adding page breaks to your PDF is a simple way to improve the readability and organization of your document. By following the steps above, you can easily add page breaks to your PDF using DomPDF Laravel.