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:

  1. Load the HTML: The HTML code is loaded into the Dompdf object using the loadHtml() method.

  2. Configure the PDF: Page orientation and paper size can be set using setPaper() method.

  3. Render the PDF: The HTML is converted to PDF using the render() method.

  4. Output the PDF: The generated PDF is stored in the $output variable.

  5. 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:

  1. Install Dompdf using Composer: composer require dompdf/dompdf
  2. Include the Dompdf namespace: use Dompdf\Dompdf;
  3. Instantiate the Dompdf class 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.