How to Convert HTML to PDF Using PHP

By Cristina Puno

Using open source scripts or online services, HTML can be converted to PHP.
i ANSI image by DBX60 from <a href='http://www.fotolia.com'>Fotolia.com</a>

PDF or Portable Document Format is a popular file type that is often used for online documents. It's great for distributing downloadable written content, and is frequently used by governments and businesses alike. Because it's a format that's familiar to all, many applications allow the user to convert other document types to the PDF format. PHP is one programming language that has a built-in ability to convert to PDF. PHP scripts can be used to transform file types such as HTML into PDF files.

HTML to PDF Using HTML2FPDF

Step 1

Download the HTML2FPDF Class Library files (see Resources).

Step 2

Paste the following code in Notepad:

require('html2fpdf.php');

$pdf=new HTML2FPDF();

$pdf->AddPage();

$fp = fopen("yourfile.html","r");

$strContent = fread($fp, filesize("sample.html"));

fclose($fp);

$pdf->WriteHTML($strContent);

$pdf->Output("yourfile.pdf");

echo "PDF file is generated successfully!";

?>

Replace "yourfile.html" with the name of the HTML file you wish to convert and "yourfile.pdf" with your desired PDF file name.

Step 3

Save it as a PHP file.

Step 4

Upload your PHP file, the HTML2FPDF Class Library files, and the HTML file that you wish to convert in the same directory on your site.

Step 5

Access the PHP file on your website to convert the HTML file to PDF.

HTML to PDF Using DOMPDF

Step 1

Download DOMPDF (see Resources).

Step 2

Paste the following code in Notepad:

require_once("dompdf_config.inc.php");

$html =

''.

'

Put your html here, or generate it with your favourite '.

'templating system.

'.

'';

$dompdf = new DOMPDF();

$dompdf->load_html($html);

$dompdf->render();

$dompdf->stream("yourhtml.pdf");

?>

In the section that indicates "Put your html here," paste the HTML code that you wish to convert to PDF.

Step 3

Save it as a PHP file.

Step 4

Upload your your PHP file and the DOMPDF files you downloaded within in the same directory on your site.

Step 5

Access the PHP file on your website to convert HTML to PDF.

Convert HTML to PDF Using PDFonFly

Step 1

Go to pdfonfly.com.

Step 2

Click on the "Text/HTML to PDF" link.

Step 3

Click on "Source" in the text editing tool and paste your HTML.

Step 4

Click on the "Create PDF" button.

×