PHP dynamically generate PDF files in Web pages detailed tutorial _php tutorial

Source: Internet
Author: User
Tags italic font pdflib
This article details the entire process of dynamically building PDF files using PHP. Experiment with open source tools such as the Free PDF Library (FPDF) or pdflib-lite, and control the PDF content format using PHP code.

Sometimes you need to control exactly how the pages you want to print are rendered. In this case, HTML is no longer the best choice. PDF files give you full control over how pages are rendered, and how text, graphics, and images are rendered on the page. Unfortunately, the API used to build the PDF file is not part of the standard PHP Toolkit. Now you need to provide a little help.

When you search the Web for PDF support for PHP, the first thing you may find is the commercial Pdflib library and its open source version pdflib-lite. These are good libraries, but the commercial version is quite expensive. The Lite repository of the Pdflib Library is distributed only as the original version, and this limitation occurs when you try to install a lite version in a managed environment.

Another option is the free PDF Library (FPDF), which is native PHP and does not require any compilation and is completely free, so you won't see the watermark as you would in an unlicensed version of Pdflib. This free PDF library is exactly what I'm going to use in this article.

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

Listing 1. XML data

 
    
  
     
   
      
    
     
      
        ... 
    
     
   
    
  
    
  
   
    
      ... 
  
    
  
   
    
      ... 
  
   
 
  

The root element of the XML is an events tag. Groups data by event, each containing multiple races. Within the events tag, there is a series of event tokens with multiple game tags in those tags. These game tags contain the names of the two teams participating in the contest and their scores in the game.

Listing 2 shows the PHP code used to read the 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 a GetResults function to read the XML file into the DOM document. Then use the DOM call to traverse through all the event and game tags to build an array of events. Each element in the sequence is a hash table that contains the event name and the array of the race item. The structure is basically a memory version of the XML structure.

To test the role of this script, an HTML export page is built, the file is read using the GetResults function, and the data is output in 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) {?>

<?php Echo ($event [' name '])?>

<?phpforeach ($event [' games '] as $game) {$s 1 = (int) $game [' score1 ']; $s 2 = (int) $game [' Score2 '];? ><?php}?>
<?php Echo ($game [' team1 '])?> <?php Echo ($s 1)?> <?php Echo ($game [' team2 '])?> <?php Echo ($s 2)?>
<?php}?>

With the code getresults.php,xml data file being uploaded to the WEB server, you can view the HTML results, which is similar to Figure 1.
Figure 1. Contest results in HTML format

In this result, the winning team was used in bold to see which teams won the game.

Build PDF

Once you have your data, you 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 app file set. In fact, as long as it's in the PHP library path, you can install it anywhere 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 ', ' ',->addpage '), $pdf->cell (40,10, "Hello world!", $pdf->output (); >

This script is actually a "Hello world", but in PDF format instead of HTML. The first action that this script performs is to use the Define statement to set the location of the FPDF font directory. Then use the Require statement to introduce the FPDF library. The script creates a FPDF object from the library, sets the font, adds a page, and then uses the Cell method to place some text on the page and output the PDF.

Figure 2 shows the results of everything under normal circumstances.

Figure 2. Hello World in PDF format

If you don't see the PDF, you might want to run the script at the command line to see if the fpdf.php file is missing or if there are other issues.

Now that the PDF is working properly, it's time to merge it with the dry-slip results file and see what can be dynamically generated. Listing 5 shows the first version of the merge operation.

Listing 5. Display the first version of the results PDF

<?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 ', ', '), foreach (GetResults () as $event) {$pdf->addpage (); $pdf Eventtable ($event); } $pdf->output ();? >

Instead of extending the FPDF category externally, we use our own PDF subclass to extend the FPDF category. Within these subclasses, we have created a new method called Eventtable, which builds a result table for a given event. In this case, we start small and output only the event name. The name is at the bottom of the script, wrapped in a foreach loop, which adds a page for each event and then calls the Eventtable method.

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

Figure 3. The first version of a dynamic PDF


Scroll down the page to show that each event is on its own page. The next step here is to start adding the results to the page.

Build Results Table

When building a PDF file, building a no-table structure is as simple as building HTML. The way to build a table is to build many different cells, such as width, font, fill color, row color, and so on.

Listing 6 shows the add code that sets the title bar of the 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 ', '");  $this->cell (40,10, $event [' name '],15);  $this->ln ();  $this->setxy (in);  $this->setfont (' ', ' B ', ' ten ');  $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 ', ', '), foreach (GetResults () as $event) {$pdf->addpage (); $pdf Eventtable ($event); } $pdf->output ();? >

The add code here is used to set the font, color, and line width. It then renders a few cells that contain four header columns. Then call the Ln method, which is equivalent to the ENTER key, to enable a new row.

When you view this script in a browser, you see something like Figure 4.

Figure 4. Page that contains the header row of the table

In Figure 4, the caption is rendered on a gray background with white text. This format helps to differentiate it from the data that is rendered under the heading. To render the match 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 ', ', '), foreach (GetResults () as $event) {$pdf->addpage (); $pdf Eventtable ($event); } $pdf->output ();? >

In addition to the header row, there is a foreach loop in the Eventtable method that iterates over each race. Figure 5 shows the code for this purpose.

Figure 5. PDF containing the result table

$fill variables can be toggled to change the color of each row in the table. The name and score of the winning team are indicated in bold, italic font so that they can be clearly displayed. Also note that the font is changed from the Arial font of the title to The Times font used to display the match content.

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

Use graphics to decorate

Adding an image to a PDF is easy. First you need to fetch an image from the Web. I crawled the logo of a dry slide team and stored it in PNG format as an image. Since then, I've been using the new code in Listing 8.

Listing 8. Add 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 ', ', '), foreach (GetResults () as $event) {$pdf->addpage (); $pdf Eventtable ($event); } $pdf->output ();? >

The key method in Listing 8 is the image method, which picks up a file name for images, locations, and widths. All other parameters are optional, so you can specify only the information you want.

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

Figure 6 shows the output of this script.

Figure 6. Completed PDF with logo image

The PDF library also provides other ways to render graphics, add flow text, add hyperlinks, manage margins, and orientation, and you have complete control over your PDF files.

Conclusion


Using the right tools, it is very easy to build PDF files from PHP. This method is ideal for printing X-tickets or notes, or for filling out forms, and for any item that requires strict control over the layout of the content.

http://www.bkjia.com/PHPjc/824611.html www.bkjia.com true http://www.bkjia.com/PHPjc/824611.html techarticle This article details the entire process of dynamically building PDF files using PHP. Experiment with open source tools such as the Free PDF Library (FPDF) or pdflib-lite, and use PHP code to control the PDF content grid ...

  • Related Article

    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.