Here is an example of how to generate an HTML to PDF file using TCPDF in Laravel 10:
- Install the
tcpdf/tcpdf-laravel
package.
composer require tcpdf/tcpdf-laravel
- Create a controller to generate the PDF file. Create a new file called
PDFController.php
in yourapp/Http/Controllers
directory. In this file, add the following code:
PHP
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use TCPDF;
class PDFController extends Controller
{
public function generatePDF()
{
$pdf = new TCPDF();
$pdf->SetTitle('My PDF Document');
$pdf->SetAuthor('Bard');
$pdf->SetSubject('This is my PDF document.');
$pdf->SetKeywords('TCPDF, Laravel');
$pdf->AddPage();
$pdf->SetFont('helvetica', 'B', 16);
$pdf->WriteHTML('<h1>This is my PDF document</h1>');
$pdf->SetFont('helvetica', '', 12);
$pdf->WriteHTML('<p>This is the content of my PDF document.</p>');
$pdf->Output('my-pdf.pdf', 'I');
}
}
- Create a route to your controller. In your
routes/web.php
file, add the following route:
Route::get('/pdf', 'PDFController@generatePDF');
- Test the route. In your terminal, run the following command to test the route:
php artisan serve
Then, open a browser and navigate to the following URL:
http://localhost:8000/pdf
This will generate a PDF file and open it in your browser.
Here is an explanation of the code:
- The
TCPDF()
method creates a new TCPDF object. - The
SetTitle()
method sets the title of the PDF document. - The
SetAuthor()
method sets the author of the PDF document. - The
SetSubject()
method sets the subject of the PDF document. - The
SetKeywords()
method sets the keywords for the PDF document. - The
AddPage()
method adds a new page to the PDF document. - The
SetFont()
method sets the font for the text. - The
WriteHTML()
method writes HTML content to the PDF document. - The
Output()
method outputs the PDF document to the browser.