Writing PDF document Builder in PHP

Source: Internet
Author: User
Tags add end functions header pdflib php file string split
One of the biggest advantages of PHP is its easy support for new technologies, which makes it easy for developers to add new modules, and the support of the world's technology community and the support of numerous extension modules makes PHP one of the most full-featured Web programming languages. Currently available expansion modules enable developers to perform IMAP and POP3 operations, dynamically generating images and Shockwave Flash animations, credit card verification, encrypted decryption of sensitive data, and the ability to parse XML-formatted data. But that's not all, and now there's a new module that can be bundled with PHP, which is the Pdflib extension module, which enables developers to dynamically generate files in the PDF (Adobe Portable Document Format) format. Let's take a look at how to use this module in PHP.

In order to enable PHP to have the ability to manipulate PDF documents, you must first install the Pdflib extension Library in your system, and if you are using a LUnix system, you can start from http://www.pdflib.com/pdflib/ index.html download one and compile, if you are using the Windows system, it is easier, just download a compiled Pdflib library, and then in the PHP configuration file in the corresponding line annotation can be removed.


If you are loading dynamically, you can also refer to the following command:

DL ("Php_pdf.dll");

In addition, you must also have an Adobe Acrobat PDF reader, which is used to browse the PDF format, and if you do not, you can download it from http://www.adobe.com/free of charge.

Once you've done your preparation, you can create a PDF file, and here's a simple example:


Create a new PDF document handle

$pdf = Pdf_new ();

Open a file

Pdf_open_file ($pdf, "pdftest.pdf");

Start a new page (A4)

Pdf_begin_page ($pdf, 595, 842);

Get and use font objects

$arial = Pdf_findfont ($pdf, "Arial", "Host", 1);

Pdf_setfont ($pdf, $arial, 10);

Output text

Pdf_show_xy ($pdf, "This is a exam of PDF Documents, It is a good Lib,", 50, 750);

Pdf_show_xy ($pdf, "If you like,please try yourself!", 50, 730);

End one page

Pdf_end_page ($pdf);

Close and save a file

Pdf_close ($pdf);


Then save it as a PHP file, browse in the browser, PHP will execute the above code, it produces a new PDF file, and saved to the specified location.

Now we analyze what code to use PHP to create a PDF file, there are four steps: 1, create a document handle; 2, register the font and color of the document; 3, write text or paint to the file handle with the function provided by Pdflib; 4, save the document.

First, create the PDF document handle, which is the following syntax:

$pdf = Pdf_new ();

This task is done by the pdf_new () function, which returns a handle to a PDF document that will be used by all subsequent operations.

The next step is to give the PDF file a name, completed by the Pdf_open_file () function, which requires the previously created file handle and the custom filename to be the parameter:

Pdf_open_file ($pdf, "pdftest.pdf");

Once we create the document, we can insert a new page with the Pdf_begin_page () function:

Pdf_begin_page ($pdf, 595, 842);

Then end the page with Pdf_end_page ().

Notice here, in the Pdf_begin_page () function, there are two other parameters, they represent the width and height of the page size, the unit is lb (point,1 point equals 1/72 inches), perhaps math is not your strong point here, PHP also provides most of the standard page size, like A4, The above example is the use of A4 size.

The code that calls between the Pdf_begin_page () function and the Pdf_end_page () function is written to the PDF document, which can be text, images, and geometry, among other things. The example just writes a line of text, gets a font first, and then writes the text to the document. It is convenient to select and register fonts through the Pdf_findfont () and Pdf_setfont () functions, and the Pdf_findfont () function prepares a font to be used in a document, with the name of the font required, the encoding used, and whether the font is to be embedded in a PDF file. The Pdf_findfont () function returns a Font object that will be used in the Pdf_setfont () function.

$arial = Pdf_findfont ($pdf, "Arial", "Host", 1);

Pdf_setfont ($pdf, $arial, 10);

Once we have the font set, we can use the Pdf_show_xy () function to write a string to the specified position in the page.

Pdf_show_xy ($pdf, "This is a exam of PDF Documents, It is a good Lib,", 50, 750);

Pdf_show_xy ($pdf, "If you like,please try yourself!", 50, 730);

The Pdf_show_xy () function is used to write content to the page, and the last two arguments are the coordinates of the string to be written, and note that the origin of the coordinates (0,0) is in the lower-left corner of the document. Once the text has been written, the page can be closed pdf_end_page (), of course, you can also write more pages. After all the pages have been written, the document is closed with the Pdf_close () function, where the document is saved to the filename and path specified when the Pdf_open_file () function is invoked, and the document handle is destroyed.

Pdflib Library can do more than this, you can also add images in the page, we take the previous file as an example, in the text below the add an image file, the following statement to implement the Add image function:

$image = Pdf_open_image_file ($pdf, "JPEG", "pdfimagetest.jpg");

Pdf_place_image ($pdf, $image, 50, 650, 0.25);

Is it simple? The Pdf_open_image_file () function opens a graphics file that accepts image types such as GIF, JPEG, TIFF, and PNG, which returns a handle to the image, and the Pdf_place_image () function takes advantage of the preceding image handle. Insert the image into the PDF document. Note that the coordinate position here is the lower left corner of the image, the last parameter is the scale factor when the image is displayed, 1 is shown as the actual size, 0.5 is shown by half of the original size.

In addition to the images that appear in the PDF document, the PDF module provides a number of functions that let us draw the geometry. For example: straight, round, rectangular and other geometric patterns, the following is a line of the implementation of the method:


$pdf = Pdf_new ();

Pdf_open_file ($pdf, "lineexam.pdf");

Pdf_begin_page ($pdf, 595, 842);

$arial = Pdf_findfont ($pdf, "Arial", "Host", 1);

Pdf_setfont ($pdf, $arial, 12);

Set the color of a line

Pdf_setcolor ($pdf, "stroke", "RGB", 0, 0, 0);

Place a logo mark in the upper left corner

$image = Pdf_open_image_file ($pdf, "JPEG", "logo.jpg");

Pdf_place_image ($pdf, $image, 50, 785, 0.5);

Draw a line under the logo

Pdf_moveto ($pdf, 20, 780);

Pdf_lineto ($pdf, 575, 780);

Pdf_stroke ($pdf);

Draw a second line at the bottom of the page

Pdf_moveto ($pdf, 20,50);

Pdf_lineto ($pdf, 575, 50);

Pdf_stroke ($pdf);

Output some text

Pdf_show_xy ($pdf, "Meng ' s Corporation", 200, 35);

Pdf_end_page ($pdf);

Pdf_close ($pdf);


As you can see from the above example, to draw a line, you need only three functions: Pdf_moveto (), Pdf_lineto (), and Pdf_stroke (). The example above is to use the Pdf_moveto ($pdf, 20, 780) function to move the cursor to the coordinates (20,780), and then use the Pdf_lineto ($pdf, 575, 780) function to define the coordinates of the other point of the line (575,780), and finally use the Pdf_ Stroke ($pdf) draw the line. Set the color function Pdf_setcolor ($pdf, "stroke", "RGB", 0, 0, 0) have several parameters, where the color fill mode has stroke, fill, both three options, color can be RGB or CMYK color scheme colors. It is noteworthy that the value used in the Pdf_setcolor () function is the percentage of the color, that is, the brightness of the color, such as: If you want to set to red (rgb:255,0,0), you can write: Pdf_setcolor ($pdf, "Stroke", "RGB ", 1, 0, 0, if you want to set to yellow, you can do this: Pdf_setcolor ($pdf," stroke "," RGB ", 1, 1, 0).

To draw rectangles and circles with fill colors, you can use the following method:

Set Fill Color

Pdf_setcolor ($pdf, "Fill", "RGB", 1, 1, 0);

Set the color of a border line

Pdf_setcolor ($pdf, "stroke", "RGB", 0, 0, 0);

Draw a rectangle, followed by the coordinates x, y, and width, height of the lower left corner of the four parameters

Pdf_rect ($pdf, 50, 500, 200, 300);

Pdf_fill_stroke ($pdf);

Pdf_setcolor ($pdf, "Fill", "RGB", 0, 1, 0);

Pdf_setcolor ($pdf, "stroke", "RGB", 0, 0, 1);

Draw the circle, the parameters are the center coordinates and the radius of the circle

Pdf_circle ($pdf, 400, 600, 100)

In addition, Pdflib provides functions to write summary information about documents that begin with pdf_set_info_* (), which can include the author, title, content, subject, etc. of the document. Here are a few common functions:

Pdf_set_info_author ($pdf, "net_lover");

Pdf_set_info_creator ($pdf, "Meng Xianhui");

Pdf_set_info_title ($pdf, "PHP Exam");

Pdf_set_info_subject ($pdf, "PHP");

Pdf_set_info_keywords ($pdf, "PHP pdf Pdflib");

When you open such a document with Acrobat Reader, you can see the information written in the menu "file"-"Document Properties"-"summary."

Speaking of which, I believe you have a basic understanding of how to use Pdflib to create PDF documents. Below, let's take a practical example to see how to serve our work. This example is based on the data provided to generate a pie chart, first of all, create a data entry form, enter the size of each piece in the pie chart. The documents are as follows:

<title> use PHP to create PDF documents (pie chart) </title>


<table cellspacing= "5" cellpadding= "5" >

<form action= "pie.php" method=post>


<td> Please enter the data values of each piece in the pie chart to split open:</td></tr>

<tr><td><input Type=text name=data></td></tr>

<tr><td><input type=submit value= "Generate PDF Pie" ></td></tr>




The following is the code for the pie.php file:


Accept Stacks

$data = $_post[' data '];

$slices = Explode (",", $data);

Initializing variables

$sum = 0;

$degrees = Array ();

$diameter = 200;

$radius = $diameter/2;

Sets the color of each pie chart, storing it with an array

$colours = Array (Array (0,0,0), Array (0,0,1), Array (0,1,0),

Array (1,0,0), Array (0,1,1), Array (1,1,0),

Array (1,0,1));

Calculate the total number

$sum = Array_sum ($slices);

Converts each piece to a corresponding percentage (360 degree circle)

for ($y =0; $y <sizeof ($slices); $y + +) {

$degrees [$y] = ($slices [$y]/$sum) * 360;


Start creating PDF Document

$pdf = Pdf_new ();

Pdf_open_file ($pdf, "chart.pdf");

Pdf_begin_page ($pdf, 500, 500);

Pdf_setcolor ($pdf, "stroke", "RGB", 1, 1, 0);

Pdf_moveto ($pdf, 250, 250);

Pdf_lineto ($pdf, 350, 250);

Pdf_stroke ($pdf);

for ($z =0; $z <sizeof ($slices); $z + +)


Set Fill Color

Pdf_setcolor ($pdf, "Fill", "RGB", $colours [$z][0],

$colours [$z][1], $colours [$z][2]);

Calculate the endpoint coordinates for each arc

$end _x = round ($radius * cos ($last _angle*pi ()/180));

$end _y = round ($radius * sin ($last _angle*pi ()/180));

Split each arc with a straight line

Pdf_moveto ($pdf, 250, 250);

Pdf_lineto ($pdf, $end _x, $end _y);

Calculate and draw an arc

Pdf_arc ($pdf, $radius, $last _angle, ($last _angle+ $degrees [$z]);

Save the last angle

$last _angle = $last _angle+ $degrees [$z];

Fill Color

Pdf_fill_stroke ($pdf);


To redraw the outline of an outer circle

Pdf_circle ($pdf, 250, 250, 100);

Pdf_stroke ($pdf);

Pdf_end_page ($pdf);

Pdf_close ($pdf);

If you want to output directly to the client, add the following code

$buf = Pdf_get_buffer ($p);

$len = strlen ($BUF);

Header ("Content-type:application/pdf");

Header ("Content-length: $len");

Header ("Content-disposition:inline; Filename=pie_php.pdf ");

Print $buf;

Pdf_delete ($p);


Run the above program and enter a different number, and you will get a different pie chart.

Pdflib is a good compatibility module, you can not only write in PHP, you can also use JAVA,C#,VB.NET,VB5/6 (activex/com), ASP (Vbscript/jscript), Borland Delphi, Windows Script HOST,COLDFUSION4.5+,C/C++,PYTHON,PERL,RPG; Supported platforms not only windows, but also Unix/linux,mac OS,IBM eserver iSeries 400 and ZSeries s/390 and so on, the specific operating environment please feel free to visit their website to get the latest information.

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.