Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Download HTML Page As PDF In PHP

Tags: html htmlpdf

Downloading a PDF file in PHP can be achieved with third-party packages such as html2pdf but first it must be converted from Html to PDF. In this following tutorial, we will utilise html2pdf to generate and download an html page.

First of all, for tutorial purposes, let’s define a simple HTML page, of course the one you want to download can be different.

HTML Page (page.html)




    My Sample HTML file

My Sample HTML File

My red text.

My blue text.

Car Make Model
Ford Focus
Ford Mondeo
Vauxhall Corsa
Vauxhall Astra

Now let’s generate a PDF from this HTML and download it.

Prerequisites

  • PHP Version 5.6 – 7.4 installed
  • Composer installed

Step 1

Download and install html2pdf into your package library.

Use the following command in Composer –

composer require spipu/html2pdf

Step 2

Ensure you are calling the package in your code with the following or similar –

use Spipu\Html2Pdf\Html2Pdf;

Step 3

Using both Html2Pdf and some native PHP we can first utilise PHP’s file_get_contents() to grab the contents of page.html and then pass it to the Html2Pdf library. Use the snippet below to carry out this set of tasks.

$html = file_get_contents('page.html');

$html2pdf = new html2pdf();
$html2pdf->writeHTML($html); // pass in the HTML
$html2pdf->output('myPdf.pdf', 'D'); // Generate the PDF and start download

The code explained

  • We use file_get_contents() and pass the parameter of the file path/filename. This reads the contents of the file and stores it in the $html variable
  • We call the library and then continue to pass in the $html variable to the writeHTML() function. This prepares the PDF conversion.
  • Next we use the output() function with the name of the PDF we want to generate and the second parameter of 'D' which instructs the output function to force the PDF file to download.

Step 4

Now, all is left to do is to execute the script, whether you want to try that by manually loading the script or assign the script to a link for users.

Check out the output PDF from this code below which as you can see has carried the styling from the HTML page too –

The post Download HTML Page As PDF In PHP appeared first on Code Wall.



This post first appeared on Code Wall - Web Development & Programming, please read the originial post: here

Share the post

Download HTML Page As PDF In PHP

×

Subscribe to Code Wall - Web Development & Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×