If you search online about how to create a PDF using PHP, you will find so many ways on how to do it. There are so many libraries that you can download together with easy to follow tutorials. But I prefer to use TCPDF because it allows me to easily create the content based on the layout that I want and I can add an SVG codes into it.

First and foremost, download the TCPDF library and place it on the desired path. Then include “tcpdf/tcpdf.php” on your main file. Example:

[code]require_once(‘tcpdf/tcpdf.php)[/code]

When creating a pdf file using PHP and TCPDF, you can either save in as a file (eg. my.pdf) or show it directly on the browser.

Create a PDF and Show it Directly on the Browser

The following codes will show a pdf with the content “Hello World!” directly on the browser.

[code]

$pdf = new TCPDF();
$pdf->SetPrintHeader(false);
$pdf->SetPrintFooter(false);
$pdf->AddPage();
$pdf->Write(0, ‘Hello World!’);
$pdf->Output();

[/code]

Create a PDF and Save It As a PDF File

The following codes will create a PDF with the content “Hello World!” and save it as my-tcpdf.pdf on the specified path.

[code]

$filename = dirname(__FILE__) . ‘my-tcpdf-‘ . time() . ‘.pdf’;

$pdf = new TCPDF();
$pdf->SetPrintHeader(false);
$pdf->SetPrintFooter(false);
$pdf->AddPage();
$pdf->Write(0, ‘Hello World!’);
$pdf->Output($filename, ‘F’);

[/code]

You can also create a pdf file dynamically and allow the user to download it. This is useful when the content of the pdf is based on the user’s input. In the code snippets below, the user will access the page (domain.com/create-pdf?name=”Annabelle”) and the pdf containing “Hello Annabelle” will be created. You can also pass user’s information from a form.

[code]

$filename = dirname(__FILE__) . ‘my-tcpdf.pdf’;

$name = $_GET[‘name’];

$pdf = new TCPDF();
$pdf->SetPrintHeader(false);
$pdf->SetPrintFooter(false);
$pdf->AddPage();
$pdf->Write(0, ‘Hello ‘ . $name . ‘!’);
$pdf->Output($filename, ‘F’);

header(‘Content-disposition: attachment; filename=MY.pdf’);
header(‘Content-type: application/pdf’);
readfile($filename);

[/code]

Note 1: Filename of the pdf on the server doesn’t have to be the same with the filename that the user can see once the file is downloaded. In the above codes, the name of the actual pdf created is my-tcpdf-<timestamp>.pdf but the user will download it as MY.pdf.

Note 2: We added the timestamp to the filename of the pdf so that multiple users can access the page and still get the pdf with the correct data.

 

Leave a Reply