How to create PDF file with PHP

There are some options available that creates PDF files with PHP functions. The simplest and the easiest method i choose and suggest is using MPDF53 library because you can add images, create forms, invoices with this library. MPDF53 library can easily generate PDF file from any HTML or PHP file with PHP which can contain images, styles sheet or inline styles. In today's post MPDF53 library, you can download it from Github from following link

https://github.com/AntonIvanchenko/hakaton/tree/master/library/MPDF53

Download the files from link and create a folder with name MPDF53. Now create any file with proper HTML tags like head, body, div etc you can create this file as PHP for dynamic entries or simple HTML for static entries. There are few things you should remember to generate proper PDF while creating HTML or PHP file.

First try to design your HTML code with table mark up then div. You can of course use div tags but try to use less. Secondly to style your markup you can create a separate style sheet and write that css file in HTML dynamically in PHP function but it is preferred that style mark up is written inside the head tag to make it easy and less complicated.

Now assuming that you have created your HTML file from which you want to generate PDF, we will write function to generate PDF.

$PdfFileName =  "yourPDFname.pdf"; //declare your pdf file name

include("MPDF53/mpdf.php");    // include the file from MPDF53

$mpdf=new mPDF('c','A4','','' , 0 , 0 , 0 , 0 , 0 , 0);
$mpdf->SetDisplayMode('fullpage');
$mpdf->list_indent_first_level = 0;  // 1 or 0 - to indent first level of a list
$mpdf->WriteHTML(file_get_contents('yourHTMLfile.html'));
$mpdf->Output($PdfFileName);

Here if you want to create PDF dynamically you can add php file with dynamic id like filename.php?id=1 instead of yourHTMLfile.html.

For styles If you want to add any style sheet you have to add few lines extra for it, the function will then become like below
$PdfFileName =  "yourPDFname.pdf";

include("MPDF53/mpdf.php"); 

$mpdf=new mPDF('c','A4','','' , 0 , 0 , 0 , 0 , 0 , 0);
$mpdf->SetDisplayMode('fullpage');
$stylesheet = file_get_contents('css/style.css');  //Add style sheet
$mpdf->WriteHTML($stylesheet, 1); // 1 shows that it is it is style only
$mpdf->list_indent_first_level = 0; 
$mpdf->WriteHTML(file_get_contents('yourHTMLfile.html'));
$mpdf->Output($PdfFileName);
If you have a small file and don't want to create any extra HTML file, you can write HTML markup inside the PHP function as well in that case you can write like below
$html= 'write your html markup and content';
$mpdf->list_indent_first_level = 0;
$mpdf->WriteHTML($html);
$mpdf->Output("$PdfFileName.pdf");
Tags: PDF
comments powered by Disqus