PHP dynamic PDF file generation on the webpage

Source: Internet
Author: User
Tags pdflib

This article details the entire process of using PHP to dynamically build a PDF file. Use the free PDF Library (FPDF), PDFLib-Lite, and other open-source tools for experimentation, and use PHP code to control the PDF content format.

Sometimes you need to accurately control how the page is displayed. In this case, HTML is no longer the best choice. The PDF file gives you full control over how pages are presented, as well as how text, graphics, and images are presented on pages. Unfortunately, the APIs used to build PDF files do not belong to the standard components of the PHP toolkit. Now you need some help.

When you search for PDF support for PHP on the internet, you may first find the commercial PDFLib library and its open-source version PDFLib-Lite. These are good libraries, but the commercial version is quite expensive. The simplified version library of the PDFLib library is only distributed as the original version. This restriction occurs when you try to install the simplified version in a hosted environment.

Another option is the free PDF Library (FPDF), which is a local PHP and does not require any compilation. It is completely free of charge. Therefore, you will not see the watermark in an unauthorized version of PDFLib. This free PDF library is exactly the one I will use in this article.

We will use the score of the Women's roller skating competition to demonstrate the process of dynamically building PDF files. These scores are obtained from the Web and converted to XML. Listing 1 shows a sample XML data file.

Listing 1. XML data

<events>  <event name="Beast of the East 2011">  <game score1="88" team1="Toronto Gore-Gore Rollergirls" team2="Montreal La Racaille" score2="11">  <game score1="58" team1="Toronto Death Track Dolls" team2="Montreal Les Contrabanditas" score2="49">   ... </game></game></event> <event name="Dustbowl Invitational 2011">   ... </event> <event name="The Great Yorkshire Showdown 2011">   ... </event></events>

The root element of XML is an events mark. Groups data by event. Each event contains multiple competitions. Within the events mark is a series of event tags, which contain multiple game tags. These game tags contain the names of the two participating teams and their scores.

Listing 2 shows the PHP code used to read XML.

<?phpfunction getResults() { $xml = new DOMDocument();  $xml->load('events.xml');  $events = array(); foreach($xml->getElementsByTagName('event') as $event) {   $games = array();  foreach($event->getElementsByTagName('game') as $game) {   $games []= array( 'team1' => $game->getAttribute('team1'),    'score1' => $game->getAttribute('score1'),    'team2' => $game->getAttribute('team2'),    'score2' => $game->getAttribute('score2') );  }  $events []= array( 'name' => $event->getAttribute('name'),   'games' => $games ); } return $events;}?>

This script implements the getResults function to read XML files into DOM documents. Then, use the DOM call to traverse all events and game tags to build an event array. Each element in the series is a hash, containing the event name and the array of the Competition Project. The structure is basically the memory version of the XML structure.

To test the function of this script, an HTML Export page is built, the getResults function is used to read files, and data is output in the form of a series of HTML tables. Listing 3 shows the PHP code used for the test.

Listing 3. Result HTML page

<?phpinclude_once('getresults.php');$results = getResults();foreach( $results as $event ) {?>

The Code getresults. php uploads the XML data file to the Web server. You can view the HTML result, which is similar to figure 1.
Figure 1. Competition Results in HTML Format

In this result, the winning team was added in bold to check which team won the match.

Build PDF

After obtaining the data, we should focus on building PDF files. The first step is to download the FPDF library and install it in the same directory as the existing application file set. In fact, as long as it is in the PHP library path, you can install it wherever you like. Track where you place the font directory, because you need to set 'fpdf _ fontpath', as shown in Listing 4.

Listing 4. PDF Hello World

<?phpdefine('FPDF_FONTPATH','/Library/WebServer/Documents/derby/font/');require( 'fpdf.php' );$pdf = new FPDF();$pdf->SetFont('Arial','',72);$pdf->AddPage();$pdf->Cell(40,10,"Hello World!",15);$pdf->Output();?>

This script is actually a "Hello World", but in PDF format rather than HTML. The first operation of this script is to use the define statement to set the position of the FPDF font directory. Then, use the require statement to introduce the FPDF library. This script creates an FPDF object from the library, sets the font, adds a page, and then places some text on the page using the Cell method, and outputs a PDF.

Figure 2 shows the results under normal circumstances.

Figure 2. PDF format Hello World

If you do not see a PDF file, you may want to run the script on the command line to check whether the fpdf. php file is lost or if there are other problems.

Since the PDF file is normally displayed, it should be merged with the roller skating result file and checked which content can be dynamically generated. Listing 5 shows the first version of the merge operation.

Listing 5. First PDF of the displayed results

<?phpdefine('FPDF_FONTPATH','/Library/WebServer/Documents/derby/font/');require( 'fpdf.php' );require( 'getresults.php' );class PDF extends FPDF{function EventTable($event){  $this->Cell(40,10,$event['name'],15);  $this->Ln();}}$pdf = new PDF();$pdf->SetFont('Arial','',48);foreach( getResults() as $event ) { $pdf->AddPage(); $pdf->EventTable($event); }$pdf->Output();?>

Instead of extending the FPDF category from the external, we use our own PDF subclass to extend the FPDF category. In these sub-classes, we create a new method named EventTable to build a result table for a given event. In this case, we start from scratch and only output the event name. The name is located at the bottom of the script and packaged in the foreach loop. The script adds a page for each event and calls the EventTable method.

You can see the output of this script in figure 3.

Figure 3. First version of dynamic PDF


Scroll down the page to show that each event is on its own page. The next step is to add the result to the page.

Build result table

When building a PDF file, building a table-free structure is as simple as building HTML. The table creation method is to build many units with different widths, fonts, fill colors, and row colors.

Listing 6 shows the Add code for setting the title bar of a table.

Listing 6. Add a result table title

<?phpdefine('FPDF_FONTPATH','/Library/WebServer/Documents/derby/font/');require( 'fpdf.php' );require( 'getresults.php' );class PDF extends FPDF{function EventTable($event){  $this->SetFont('','B','24');  $this->Cell(40,10,$event['name'],15);  $this->Ln();  $this->SetXY( 10, 45 );  $this->SetFont('','B','10');  $this->SetFillColor(128,128,128);  $this->SetTextColor(255);  $this->SetDrawColor(92,92,92);  $this->SetLineWidth(.3);  $this->Cell(70,7,"Team 1",1,0,'C',true);  $this->Cell(20,7,"Score 1",1,0,'C',true);  $this->Cell(70,7,"Team 2",1,0,'C',true);  $this->Cell(20,7,"Score 2",1,0,'C',true);  $this->Ln();}}$pdf = new PDF();$pdf->SetFont('Arial','',10);foreach( getResults() as $event ) { $pdf->AddPage(); $pdf->EventTable($event); }$pdf->Output();?>

The code added here is used to set the font, color, and row width. It then presents several cells that contain four title columns. Call the Ln method (equivalent to the Enter key) to enable a new line.

When viewing this script in a browser, You can see content similar to Figure 4.

Figure 4. page containing the table's title row

In Figure 4, the title is displayed in a gray background with white text. This format helps distinguish it from the data displayed under the title. To present the competition results, add the following code in listing 7.

Listing 7. Add a complete result table

<?phpdefine('FPDF_FONTPATH','/Library/WebServer/Documents/derby/font/');require( 'fpdf.php' );require( 'getresults.php' );class PDF extends FPDF{function EventTable($event){  $this->SetFont('','B','24');  $this->Cell(40,10,$event['name'],15);  $this->Ln();  $this->SetFont('','B','10');  $this->SetFillColor(128,128,128);  $this->SetTextColor(255);  $this->SetDrawColor(92,92,92);  $this->SetLineWidth(.3);  $this->Cell(70,7,"Team 1",1,0,'C',true);  $this->Cell(20,7,"Score 1",1,0,'C',true);  $this->Cell(70,7,"Team 2",1,0,'C',true);  $this->Cell(20,7,"Score 2",1,0,'C',true);  $this->Ln();  $this->SetFillColor(224,235,255);  $this->SetTextColor(0);  $this->SetFont('');  $fill = false;  foreach($event['games'] as $game)  {    $this->SetFont('Times',((int)$game['score1']>(int)$game['score2'])?'BI':'');    $this->Cell(70,6,$game['team1'],'LR',0,'L',$fill);    $this->Cell(20,6,$game['score1'],'LR',0,'R',$fill);    $this->SetFont('Times',((int)$game['score1']<(int)$game['score2'])?'BI':'');    $this->Cell(70,6,$game['team2'],'LR',0,'L',$fill);    $this->Cell(20,6,$game['score2'],'LR',0,'R',$fill);    $this->Ln();    $fill =! $fill;  }  $this->Cell(180,0,'','T');}}$pdf = new PDF();$pdf->SetFont('Arial','',10);foreach( getResults() as $event ) { $pdf->AddPage(); $pdf->EventTable($event); }$pdf->Output();?>

In addition to the row title, there is also a foreach loop in the EventTable method, which will iterate in each competition. Figure 5 shows the code for this purpose.

Figure 5. PDF containing the result table

The $ fill variable can be switched to change the color of each row in the table. The names and scores of the winning teams are displayed in bold and italic fonts, so that they can be clearly displayed. Note that the font is changed from the Arial font of the title to the Times font used to display the game content.

To complete the sample code, you need to add some images.

Use graphs for Modification

It is very easy to add images to PDF files. First, capture an image from the Web. I crawled a logo of the roller skating corps and stored it as a PNG image. Since then, I have been using the new code in listing 8.

Listing 8. Adding a logo image

<?phpdefine('FPDF_FONTPATH','/Library/WebServer/Documents/derby/font/');require( 'fpdf.php' );require( 'getresults.php' );class PDF extends FPDF{function EventTable($event){  $this->Image('logo.png',5,5,33);  $this->SetXY( 40, 15 );  $this->SetFont('','B','24');  $this->Cell(40,10,$event['name'],15);  $this->Ln();  $this->SetXY( 10, 45 );  $this->SetFont('','B','10');  $this->SetFillColor(128,128,128);  $this->SetTextColor(255);  $this->SetDrawColor(92,92,92);  $this->SetLineWidth(.3);  $this->Cell(70,7,"Team 1",1,0,'C',true);  $this->Cell(20,7,"Score 1",1,0,'C',true);  $this->Cell(70,7,"Team 2",1,0,'C',true);  $this->Cell(20,7,"Score 2",1,0,'C',true);  $this->Ln();  $this->SetFillColor(224,235,255);  $this->SetTextColor(0);  $this->SetFont('');  $fill = false;  foreach($event['games'] as $game)  {   $this->SetFont('Times',((int)$game['score1']>(int)$game['score2'])?'BI':'');   $this->Cell(70,6,$game['team1'],'LR',0,'L',$fill);   $this->Cell(20,6,$game['score1'],'LR',0,'R',$fill);   $this->SetFont('Times',((int)$game['score1']<(int)$game['score2'])?'BI':'');   $this->Cell(70,6,$game['team2'],'LR',0,'L',$fill);   $this->Cell(20,6,$game['score2'],'LR',0,'R',$fill);   $this->Ln();   $fill =! $fill;  }  $this->Cell(180,0,'','T');}}$pdf = new PDF();$pdf->SetFont('Arial','',10);foreach( getResults() as $event ) { $pdf->AddPage(); $pdf->EventTable($event); }$pdf->Output();?>

The key method in listing 8 is the Image method, which selects a file name for the Image, position, and width. All other parameters are optional, so you only need to specify the information you want.

Some new calls to SetXY will move the text and table left and right to an appropriate position to prevent it from overwriting the image.

Figure 6 shows the output of this script.

Figure 6. Completed PDF with logo Images

The PDF Library also provides other methods to present images, add stream text, add hyperlinks, manage margins and directions, and you can fully control your PDF files.

Conclusion


Using suitable tools, it is very easy to build PDF files through PHP. This method is ideal for printing x-vote or ticket, filling out forms, and any project that requires strict control of the content layout.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.