PHP has several libraries for generating PDF documents. This is shows how to use the popular fpdf library. The FPDF library is a set of PHP code you include in your scripts with the require function, so it doesn't require any server-side configuration or support, meaning you can use it even without support from your host.
The basic concepts of the structure and features of a PDF file should be common to all the pdf libraries, however. This library (FPDF) is available at http://www.fpdf.org.
A PDF document is made up of a number of pages. Each page contains text and/or images. This section shows you how to make a document, create pages in that document, put text onto the pages, and send the pages back to the browser when you're done.
A Simple Example
Let's start with a simple PDF document. Example below simply places "Hello Out There!" on a page and then displays the resulting PDF document.
require("../fpdf/fpdf.php"); // path to fpdf.php
$pdf = new FPDF( );
$pdf->AddPage( );
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello Out There!');
$pdf->Output( );
?>
Initializing the Document
In Example above, we started by making reference to the FPDF library with the require function. Then the code created a new instance of the FPDF object with the 'new' keyword. You will note that all the calls to the new fpdf instance are object-oriented calls to methods in that object. After you have created the new instance of the FPDF object, you will need to add at least one page to the objectso the AddPage method is called. Next, you need to set the font for the output you are about to generate with the SetFont call. Then using the cell method call, you can place the output on your created document. To send all your work to the browser, simply use the Output method.
Outputting Basic Text - Cells
The cell concept in the FPDF Library is that of a rectangular area on the page that you can create and control. This cell can have a height, width, a border, and of course can contain text. The basic syntax for the cell method is as follows:
Cell(float w [, float h [, string txt [, mixed border [, int ln [, string align [, int fill [, mixed link]]]]]]])
The first option is the width, then the height, then the text to be outputted, then border, then new line control, then its alignment, any fill colour for the text, and finally if you want the text to be an HTML link. So, for example, if we want to change our original example to have a border and be center aligned we would change the cell code to the following:
$pdf->Cell(90,10,'Hello Out There!',1,0,'C');
The cell method is used extensively while generating PDF documents with fpdf, so you would be well served if you spent the time needed to learn the ins and outs of this method.
24 June 2008
PDF Extensions of PHP - A Simple Example
Subscribe to:
Post Comments (Atom)
Labels:









No comments:
Post a Comment
Silahkan isi komentar Anda tentang artikel saya :