This PHP tutorial will show you how you can create .pdf files directly from PHP. It will be divided into three parts (tutorials) because it is longer and more difficult than the ones I posted until now.
You have multiple choices on how to create PDF using PHP. One of them would be to use PDFLib, which is a PHP module. A problem which can appear is that if you are on a shared webhosting server this module may not be installed. Another one is that you must keep in mind the version of PHP that you are using and also PDFlib. This could be difficult for beginners.
More information you can find at: PDFLib. Another approach would be to make use of a class called FDPF. The advantage of this is that the class is not using PDFLib and it’s free. You only need the PHP file containing the class and a directory with all the fonts. You can check here: FDBF .
Let’s start by showing some examples. As I said this will be a three part tutorial.
Okay! Let’s discuss the code: we create the object that will represent the pdf document with new FPDF(). This can take arguments: P or L (Portrait or Landscape), second one is the measurement unit in mm, cm or pt (points) and the thirt argument can be the format of the document, A4, A3 and so on. If no arguments are specified as in our example the default values are Portrait, mm, A4.
Using AddPage() we are initializing the page. After that we are setting the font using SetFont().
Then comes the text. 25 represents the distance X from left, and 40 the top distance. With Output() we are displaying the pdf. Output can take parameters, for example the file which we want to use and the action that can be applied to that file:
- I – sends the file to be displayed in browser.
- D – opens the option to download of PDF document.
- F – saves the file on server (must have rights to write) .
- S – returns the file as string, the name is ignored.
We can create cells (similar to divs in HTML), you can define the surface, the background..
Cell() can take more arguments;
- the first two represent the length and the height of the cell.
- the next argument is the text displayed in the cell.
- the other arguments are for border, the position of the pointer in the page.
- besides these Cell() can another two arguments for background or for link.
$pdf->Output(); // Send output to the browser.
?>
The code above is explained using comments. That’s it for now!
I hope you enjoyed this PHP tutorial that shows you how to create PDF directly from PHP.
There will be two more parts to this tutorial.
Leave a Reply