PHP dynamic PDF file generation on the webpage

Source: Internet
Author: User
Tags pdflib
This article mainly introduces the PHP detailed tutorial on dynamic PDF file generation on the web page. This article uses a requirement to introduce the practice of each step in detail and provides a large number of image descriptions, for more information, see

This article mainly introduces the PHP detailed tutorial on dynamic PDF file generation on the web page. This article uses a requirement to introduce the practice of each step in detail and provides a large number of image descriptions, for more information, see

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

... ... ...

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) {?> <? Php echo ($ event ['name'])?> <? Phpforeach ($ event ['games'] as $ game) {$ s1 = (int) $ game ['score1']; $ s2 = (int) $ game ['score2'];?> <? Php }?>

<? Php echo ($ game ['team1'])?> <? Php echo ($ s1)?> <? Php echo ($ game ['team2'])?> <? Php echo ($ s2)?>
<? Php }?>

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 (, $ event ['name'], 15 ); $ this-> Ln () ;}$ pdf = new PDF (); $ pdf-> SetFont ('arial', '', 48); foreach (getResults () as $ event) {$ pdf-> AddPage (); $ pdf-> EventTable ($ event);} $ pdf-> Output ();?>

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.