Compile a PDF document generator in PHP

Source: Internet
Author: User
Tags pdflib php pdf

One of the biggest advantages of PHP is that it supports new technologies very easily. the scalability of this language allows developers to easily add new modules, in addition, the support of technical groups all over the world and the support of many extension modules make PHP the most functional webProgramming Language1. Currently, the extended modules allow developers to perform IMAP and POP3 operations, dynamically generate images and Shockwave Flash animations, perform credit card verification, and encrypt and decrypt sensitive data, it can also parse data in XML format. But this is not all. Now, another new module can be bound to PhP, namely the pdflib extension module, which allows developers to dynamically generate PDF (Adobe Portable Document Format) the following describes how to use this module in PHP.

To enable PHP to operate PDF files, you must first install the pdflib extension library in your system. If you are using an Lunix system, you can.

Extension = php_cmd.dll

For dynamic loading, refer to the following command:

DL ("php_cmd.dll ");

In addition, you must have an Adobe Acrobat PDF reader to browse the PDF format. If you do not have one, you can download it from http://www.adobe.com/for free.

Once you have prepared a PDF file, you can create a PDF file. The following is a simple example:

<? PHP

// Create a new pdf document handle

$ PDF = pai_new ();

// Open a file

Pai_open_file ($ PDF, "Your testbench ");

// Start a new page (A4)

__Begin_page ($ PDF, 595,842 );

// Obtain and use the font object

$ Arial = pai_findfont ($ PDF, "Arial", "host", 1 );

Performance_setfont ($ PDF, $ Arial, 10 );

// Output text

Pai_show_xy ($ PDF, "This is an exam of PDF documents, it is a good Lib,", 50,750 );

Pai_show_xy ($ PDF, "if you like, please try yourself! ", 50,730 );

// End page

Pai_end_page ($ PDF );

// Close and save the file

Pai_close ($ PDF );

?>

Save it as a PHP file and browse it in the browser. Then PHP will execute the aboveCodeIt generates a new pdf file and saves it to the specified location.

Now let's analyze what code we need 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, use the functions provided by pdflib to write text or drawing to the file handle; 4. Save the document.

First, create a PDF document handle. The syntax is as follows:

$ PDF = pai_new ();

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

The next step is to give the PDF file a name, which is completed by the pai_open_file () function. It requires the previously created file handle and custom file name as parameters:

Pai_open_file ($ PDF, "Your testbench ");

Once the document is created, you can use the plu_begin_page () function to insert a new page:

__Begin_page ($ PDF, 595,842 );

Then end the page with pai_end_page.

Note that in the pdf_begin_page () function, there are two other parameters, which respectively represent the width and height of the page, in the unit of LBS (point, 1 lb equals 1/72 inch ), maybe mathematics is not your strength here. php also provides most standard page sizes, such as A4. The above example uses A4 size.

The code between the pdf_begin_page () function and the pdf_end_page () function is written to the PDF document. The content can be text, images, and ry. In this example, only one line of text is written. First, a font is obtained and the text is written to the document. It is very convenient to select and register the font through the pai_findfont () and pai_setfont () functions. The pai_findfont () function has prepared a font to be used in the document, the required parameters include the font name, encoding used, and whether the font should be embedded in the PDF file. The pai_findfont () function returns a font object, which will be used in the pai_setfont () function.

$ Arial = pai_findfont ($ PDF, "Arial", "host", 1 );

Performance_setfont ($ PDF, $ Arial, 10 );

Once the font is set, you can use the pai_show_xy () function to write a string to a specified position on the page.

Pai_show_xy ($ PDF, "This is an exam of PDF documents, it is a good Lib,", 50,750 );

Pai_show_xy ($ PDF, "if you like, please try yourself! ", 50,730 );

The pai_show_xy () function is used to write content to the page. The last two parameters are the coordinates of the string to be written. Note that the coordinate origin () is in the lower left corner of the document. Once the text is written, the page can be closed with pai_end_page (). Of course, you can also write more pages. After writing all the pages, close the document using the pai_close () function. Then the document is saved to the file name and path specified when the pai_open_file () function is called, and the document handle is destroyed.

The pdflib library can do more than this. You can also add images to the page. For example, add an image file under the text file, the following statement adds an image:

$ Image = pai_open_image_file ($ PDF, "Jpeg", "pdfimagetest.jpg ");

Pai_place_image ($ PDF, $ image, 50,650, 0.25 );

Is it easy? The pai_open_image_file () function opens an image file. Acceptable image types include: GIF, JPEG, Tiff, and PNG. This function returns an image handle. The pai_place_image () function uses the preceding image handle, insert an image to a PDF file. Note that the coordinates here refer to the lower left corner of the image. The last parameter is the proportional factor when the image is displayed. 1 is displayed in the same size as the actual size, and 0.5 is displayed in half of the original size.

In addition to drawing images in PDF documents, the PDF module also provides a number of functions for us to draw ry. For example, for geometric patterns such as straight lines, circles, and rectangles, the following describes how to draw a straight line:

<? PHP

$ PDF = pai_new ();

Pai_open_file ($ PDF, "lineexam.pdf ");

__Begin_page ($ PDF, 595,842 );

$ Arial = pai_findfont ($ PDF, "Arial", "host", 1 );

Performance_setfont ($ PDF, $ Arial, 12 );

// Set the color of the line

__Setcolor ($ PDF, "stroke", "RGB", 0, 0, 0 );

// Place a logo in the upper left corner.

$ Image = pai_open_image_file ($ PDF, "Jpeg", "logo.jpg ");

Pai_place_image ($ PDF, $ image, 50,785, 0.5 );

// Draw a straight line under the logo

Pai_moveto ($ PDF, 20,780 );

Pai_lineto ($ PDF, 575,780 );

Performance_stroke ($ PDF );

// Draw another line at the bottom of the page

Pai_moveto ($ PDF, 20, 50 );

Pai_lineto ($ PDF, 575, 50 );

Performance_stroke ($ PDF );

// Output some text

Performance_show_xy ($ PDF, "Meng's corporation", 200, 35 );

Pai_end_page ($ PDF );

Pai_close ($ PDF );

?>

As shown in the preceding example, to draw a straight line, you only need three functions: pai_moveto (), pai_lineto (), and pai_stroke (). In the above example, we first use the pdf_moveto ($ PDF, 20,780) function to move the cursor to the coordinate (20,780), and then use pdf_lineto ($ PDF, 575,780) the function defines the coordinates (575,780) of another vertex of a straight line, and draws a line using pai_stroke ($ PDF. The color function pdf_setcolor ($ PDF, "stroke", "RGB", 0, 0, 0) has several parameters, the color fill mode includes three options: stroke, fill, and both. The color can be the color value of the RGB or CMYK color scheme. It is worth noting that the value used in the pai_setcolor () function is the percentage of the color, that is, the brightness of the color. For example, if you want to set it to red (RGB: 255, 0, 0 ), you can write: pdf_setcolor ($ PDF, "stroke", "RGB", 1, 0, 0). To set it to yellow, you can do this: pdf_setcolor ($ PDF, "stroke", "RGB", 1, 1, 0 ).

To draw a rectangle and a circle with a fill color, you can use the following method:

// Set the fill color

__Setcolor ($ PDF, "fill", "RGB", 1, 1, 0 );

// Set the border line color

__Setcolor ($ PDF, "stroke", "RGB", 0, 0, 0 );

// Draw a rectangle. The following four parameters are the coordinates x, y, width, and height in the lower left corner.

Performance_rect ($ PDF, 50,500,200,300 );

Pai_fill_stroke ($ PDF );

__Setcolor ($ PDF, "fill", "RGB", 0, 1, 0 );

__Setcolor ($ PDF, "stroke", "RGB", 0, 0, 1 );

// Draw the circle. The parameters are the coordinates of the center and the radius of the circle.

Pai_circle ($ PDF, 400,600,100)

In addition, pdflib provides functions for writing document summary information. These functions start with pai_set_info _ * (). These functions can include the author, title, content, and topic of a document. Below are several common functions:

__Set_info_author ($ PDF, "net_lover ");

__Set_info_creator ($ PDF, "Meng xianhui ");

Pai_set_info_title ($ PDF, "php exam ");

Pai_set_info_subject ($ PDF, "php ");

Pai_set_info_keywords ($ PDF, "php PDF pdflib ");

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

Speaking of this, I believe you have a basic understanding of how to use pdflib to create PDF documents. Next, let's take a practical example to see how to serve our work. In this example, a pie chart is generated based on the provided data. First, a data input form is created to enter the size of each segment in the pie chart. The file is as follows:

<HTML>

<Head>

<Title> Use PHP to create a PDF document (pie chart) </title>

</Head>

<Body>

<H3> pie chart generator

<Table cellspacing = "5" cellpadding = "5">

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

<Tr>

<TD> enter the data values of each segment in the pie chart and separate them with (,): </TD> </tr>

<Tr> <TD> <input type = text name = data> </TD> </tr>

<Tr> <TD> <input type = submit value = "generate PDF pie chart"> </TD> </tr>

</Form>

</Table>

</Body>

</Html>

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

<? PHP

// Accept the library

$ DATA = $ _ post ['data'];

$ Slices = explode (",", $ data );

// Initialize the variable

$ Sum = 0;

$ Degrees = array ();

$ Diameter = 200;

$ Radius = $ diameter/2;

// Set the color of each pie chart, which is stored in arrays.

$ Colours = array (Array (0, 0), array (0, 0, 1), array (0, 0 ),

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

Array (1, 0, 1 ));

// Calculate the total value

$ Sum = array_sum ($ slices );

// Convert each part into a corresponding percentage (360 degrees circle)

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

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

}

// Start creating a PDF document

$ PDF = pai_new ();

Pai_open_file ($ PDF, "chart.pdf ");

__Begin_page ($ PDF, 500,500 );

__Setcolor ($ PDF, "stroke", "RGB", 1, 1, 0 );

Pai_moveto ($ PDF, 250,250 );

Pai_lineto ($ PDF, 350,250 );

Performance_stroke ($ PDF );

For ($ z = 0; $ z <sizeof ($ slices); $ Z ++)

{

// Set the fill color

__Setcolor ($ PDF, "fill", "RGB", $ colours [$ Z] [0],

$ Colours [$ Z] [1], $ colours [$ Z] [2]);

// Calculate the end coordinate of each arc

$ End_x = round (250 + ($ radius * Cos ($ last_angle * Pi ()/180 )));

$ End_y = round (250 + ($ radius * sin ($ last_angle * Pi ()/180 )));

// Use a straight line to separate each arc

Pai_moveto ($ PDF, 250,250 );

__Lineto ($ PDF, $ end_x, $ end_y );

// Calculate and draw an arc

Pdf_arc ($ PDF, 250,250, $ radius, $ last_angle, ($ last_angle + $ degrees [$ Z]);

// Save the final angle

$ Last_angle = $ last_angle + $ degrees [$ Z];

// Fill color

Pai_fill_stroke ($ PDF );

}

// Redraw the outer contour

Pai_circle ($ PDF, 250,250,100 );

Performance_stroke ($ PDF );

Pai_end_page ($ PDF );

Pai_close ($ PDF );

// If You Want To directly output the data to the client, add the following code

$ Buf = pai_get_buffer ($ P );

$ Len = strlen ($ BUF );

Header ("Content-Type: Application/pdf ");

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

Header ("content-Disposition: inline; filename=pie_php ");

Print $ Buf;

Performance_delete ($ P );

?>

Run the precedingProgramAnd enter different values to obtain different pie charts.

pdflib is a compatible module. You can not only write it in PHP, but also use Java, C #, and VB. net, vb5/6 (ActiveX/COM), ASP (VBScript/JScript), Borland Delphi, Windows Script Host, coldfusion4.5 +, C/C ++, Python, Perl, and RPG; supported platforms include not only windows, but also Unix/Linux, Mac OS, IBM eserver iseries 400, and zseries S/390, for specific operating environment, please visit their website at any time to obtain 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.