Easy HTML to PDF with PHP

Usually a webmaster has the access to the ftp to manage the website files and nothing more. And I think that tons of admins have the same problem: how to generate a PDF file from a webpage? This is a hard task if you don’t have access to the shell of  your system (lots of libraries must be installed, for example, from the php command line) and maybe you don’t want to spend money to accomplish this task with other solutions.

I googled it hundred times but none of the websites found really soddisfied me.

So I want to share with you an easy-to-use library found some years ago and used for some projects. This library is very easy because you can really transform an HTML page into a simple PDF document and then adjust your CSS as you like.

The lib contains lots of examples, here the classic usage:

    
<?php
    /* ob_start(); MUST be called as first thing. Don't move it from here. */
    ob_start();
?>

	
		My title
		
	
	
<?php

		/* My variables from POST/GET */
		if(isset($_REQUEST['myvar']))
			$myvar=$_REQUEST['myvar'];

		/* Put here as much code as you want!  */

		/* Put down here function1, function 2 etc...*/
		function foo(){}
		function bar(){}

		/* Keep here the generation of the PDF. Edit the path of lib if necessary */
		$content = ob_get_clean();

			// convert in PDF
			require_once(dirname(__FILE__).'./html2pdf/html2pdf.class.php');
			try
			{
				$html2pdf = new HTML2PDF('P', 'A4', 'en');
				//$html2pdf->setModeDebug();
				$html2pdf->setDefaultFont('Arial');
				$html2pdf->writeHTML($content, isset($_GET['vuehtml']));
				$html2pdf->Output('output.pdf');
			}
			catch(HTML2PDF_exception $e) {
				echo $e;
				exit;
			}
		/* END of generation */

?>

	
	


    

To download the lib click  HERE.

Enjoy!

Be the first to comment

Leave a Reply

Your email address will not be published.


*