Tuesday 4 December 2012

HTML to PDF Conversion in PHP

Today I'm presenting you one interesting feature in PHP, it is nothing but html to pdf conversion just using a simple php scripts. For this purpose we will be using a 3rd party library which can make our job easy.

The third party library I'm introducing is "HTML2PDF". For creating a pdf out of html file please refer below:

test.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Test HTML</title>
</head>

<body>
<h1>HTML TO PDF</h1>
    <p>Hello World!</p>
</body>
</html>

Above is a html snippet. Here it is a demo to convert the above html file to pdf. See the code below.


index.php


<?php
error_reporting(0);
require("html2fpdf.php");          

$htmlFile = "test.html";
$buffer = file_get_contents($htmlFile);

$pdf = new HTML2FPDF('P', 'mm', 'Letter');
$pdf->AddPage();
$pdf->WriteHTML($buffer);
$pdf->Output('test.pdf', 'F');
?>

"html2fpdf.php" included is the library. Click here to download.

It the simplest method available to convert html to pdf. Please suggest any idea if you find any.

Thank You!

2 comments:

  1. AddPage(); $pdf->WriteHTML($buffer); $pdf->Output('test.pdf', 'F'); ?>
    it displaying above line.

    ReplyDelete
    Replies
    1. Can you explain? Have you included the "html2fpdf.php" library to the script?

      Delete