PHP for dynamically generating PDF documents from HTML
PHP for Dynamically Generating PDF Documents from HTML
Code Solution:
use Dompdf\Dompdf;
// PHP script to generate PDF from HTML
$html = '<h1>Hello, World!</h1><p>This is a PDF generated from HTML.</p>';
$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();
$output = $dompdf->output();
// Save the PDF to the server
file_put_contents('my-pdf.pdf', $output);
// Redirect the user to the PDF
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="my-pdf.pdf"');
header('Content-Length: ' . strlen($output));
echo $output;
Explanation:
-
Load the HTML: The HTML code is loaded into the Dompdf object using the
loadHtml()method. -
Configure the PDF: Page orientation and paper size can be set using
setPaper()method. -
Render the PDF: The HTML is converted to PDF using the
render()method. -
Output the PDF: The generated PDF is stored in the
$outputvariable. -
Save or Redirect the PDF: Depending on the requirement, the PDF can be saved to the server using
file_put_contents(), or redirected to the user’s browser for download.
Implementation:
Requirements:
- PHP >= 5.6
- Dompdf library
Steps to Integrate Dompdf:
- Install Dompdf using Composer:
composer require dompdf/dompdf - Include the Dompdf namespace:
use Dompdf\Dompdf; - Instantiate the
Dompdfclass and perform the following steps as shown in the code snippet.
Tips:
- Use CSS to style the HTML before converting it to PDF.
- Set appropriate page margins and headers/footers.
- Generate PDF from dynamic data by converting it to HTML first.
- Use external libraries for advanced features like table of contents or page numbering.