PDF Generation
PDF Generation
PDFs can be generated easily in Hazaar using the Hazaar\File\PDF class. This class extends the standard Hazaar\File class but includes a filter that automatically converts any HTML content set into the file into a PDF document using the DOMPDF library.
Because Hazaar\File\PDF is just a file object, you can save it to disk, or return it directly from a controller action to have it automatically downloaded by the browser.
Basic Usage
To generate a PDF, instantiate the Hazaar\File\PDF object and set some content.
$pdf = new \Hazaar\File\PDF();
$pdf->setContents('<h1>This is a test PDF</h1>');
$pdf->save('test.pdf');This will create a file named test.pdf in the current working directory containing the rendered PDF.
Returning from a Controller
You can also return the Hazaar\File\PDF object directly from a controller action or route closure. The framework will automatically detect that you are returning a file and will wrap it in a Hazaar\Controller\Response\PDF object to be sent to the browser with the correct headers.
use Hazaar\File\PDF;
Router::get('/pdf', function () {
$pdf = new PDF();
$pdf->setContents('<h1 style="color: #554d7c;">Hello, World</h1><p>This is a PDF response!</p>');
return $pdf;
});Or in a controller class:
namespace App\Controller;
use Hazaar\Controller\Action;
use Hazaar\File\PDF;
class Main extends Action {
public function pdf() {
$pdf = new PDF();
$pdf->setContents('<h1>This is a test PDF</h1>');
return $pdf;
}
}Rendering from a File
If you have your HTML stored in a file, you can load it using file_get_contents() and pass it to setContents().
$pdf = new \Hazaar\File\PDF();
$content = file_get_contents(\Hazaar\Loader::getFilePath(FILE_PATH_VIEW, 'pdf/testpdf.html'));
$pdf->setContents($content);
return $pdf;Rendering from a Template
You can also use the Hazaar MVC template engine to render a view and then use that output to generate your PDF. This allows you to easily inject dynamic data into your PDF documents.
$template = new \Hazaar\View('pdf/invoice');
$template->items = [
['item' => 'Widget', 'cost' => 10.00],
['item' => 'Gadget', 'cost' => 20.00]
];
$pdf = new \Hazaar\File\PDF();
$pdf->setContents($template->render());
return $pdf;Rendering a Web Page
It is also possible to render a PDF directly from a URL using the setSource() method.
$pdf = new \Hazaar\File\PDF();
$pdf->setSource("http://www.google.com");
return $pdf;This will download the HTML from the specified URL and render it as a PDF.
Installation
The PDF generation feature requires the dompdf/dompdf library. You can install it using Composer:
composer require dompdf/dompdfThe Hazaar\File\PDF class checks for the existence of the Dompdf\Dompdf class and will throw an exception if it is not found.