How to write PDF document generator in PHP

Source: Internet
Author: User
Tags pdflib php pdf
How to write PDF document generator in PHP

One of the biggest advantages of PHP is that its support for new technologies is easy, and the extensibility of the language makes it easy for developers to add new modules, and the support of the world-wide technology community and the support of many extension modules make PHP one of the most versatile web programming languages. The available expansion modules have enabled developers to perform IMAP and POP3 operations, dynamically generate images and Shockwave Flash animations, perform credit card verification, encrypt and decrypt sensitive data, and parse data in XML format. But that's not all, and now there's a new module that can be bound to PHP, which is the pdflib extension, which enables developers to dynamically produce files in the PDF format (Adobe Portable Document 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 the LUnix system, you can http://www.pdflib.com/pdflib/ index.html download one and compile, if you are using a Windows system, it is more simple, just need to download a compiled Pdflib library, and then in the PHP configuration file to the corresponding line of comments removed.


Extension=php_pdf.dll


If it is a dynamic mount, you can also refer to the following command:


DL ("Php_pdf.dll");


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

Once you are ready to create a PDF file, here is a simple example:


Create a new handle to a PDF document

$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, "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 a page

Pdf_end_page ($pdf);


Close and save the file

Pdf_close ($pdf);

?>

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

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

First, create a PDF document handle with 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, which is done by the Pdf_open_file () function, which requires the file handle that was created earlier and the custom file name to do the argument:


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


Once we have created the document, we can insert a new page in it using the Pdf_begin_page () function:


Pdf_begin_page ($pdf, 595, 842);


Then end the page with Pdf_end_page ().

Note here, in the Pdf_begin_page () function, there are two other parameters, they represent the width and height of the page size, in pounds (point,1 points equal to 1/72 inches), perhaps here math is not your strength, PHP also provides most of the standard page size, such as A4, The above example is the use of A4 size.

The code between the call to the Pdf_begin_page () function and the Pdf_end_page () function is written to the PDF document, which can be text, images, geometry, and so on. In the example, just write a line of text, get a font first, and then write the text into 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, the required parameters are the name of the font, the encoding used, and whether the font is to be embedded in the 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 set the font, we can use the Pdf_show_xy () function to write the string to the specified position in the page.


Pdf_show_xy ($pdf, "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 to the page, and the last two parameters are the coordinate position of the string to be written, noting that the origin of the coordinates (0,0) is in the lower-left corner of the document. Once the text is finished, the page closes Pdf_end_page (), and of course you can write more pages. After all the pages have been written, close the document with the Pdf_close () function, and the document is saved back to the file name and path specified when the Pdf_open_file () function is called, and the document handle is destroyed.

Pdflib Library can do things far more than these, but also in the page to add images, we take the previous file as an example, in the text to add an image file, the following statement to achieve the added image function:


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

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


Isn't 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 the image handle, and the Pdf_place_image () function takes advantage of the previous image handle, Insert the image into the PDF document. Note that the coordinate position here refers to the lower left corner of the image, the last parameter is the scale factor when the image is displayed, 1 is the same as the actual size, and 0.5 is displayed as half the original size.

In addition to drawing images that appear in PDF documents, the PDF module provides many functions that let us draw geometry. For example: Straight lines, circles, rectangles and other geometric patterns, the following is a picture of a straight line implementation 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 in the top 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 another 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 straight 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 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. The color-setting function Pdf_setcolor ($pdf, "stroke", "RGB", 0, 0, 0) has several parameters, in which the color fill pattern has stroke, fill, both three options, and the color can be the color value of the RGB or CMYK color scheme. It is worth noting 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 the border line

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


Draw a rectangle, the following four parameters are the coordinates x, y and width, height of the lower left corner, respectively

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, respectively


Pdf_circle ($pdf, 400, 600, 100)


In addition, Pdflib provides functions for writing document summary information 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 in 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 create PDF documents using Pdflib. Below, let's take a practical example to see how we serve our work. The example is to generate a pie chart based on the data provided, first, create a data entry form and enter the size of each piece in the pie chart. The file is as follows:


Create PDF documents with PHP (pie chart)

Pie chart Builder


Here is the code for the pie.php file:


Accept the Library

$data = $_post[' data '];

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


Initialize variables

$sum = 0;

$degrees = Array ();

$diameter = 200;

$radius = $diameter/2;


Set the color of each pie chart and store 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 value

$sum = Array_sum ($slices);


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

for ($y =0; $y < p="">

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

}


Start creating PDF Documents

$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 < p="">

{

Set Fill Color

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

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


Calculate the end coordinates of each arc

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

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


Split each piece of 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);

}


Redraw the outline of the 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 value, 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 are not just windows, but Unix/linux,mac os,ibm eserver iSeries 400 and ZSeries s/390, etc., the specific operating environment please feel free to visit their website to get the latest information.

The above describes how to use PHP to write a PDF document generator, including aspects of the content, I hope the PHP tutorial interested in a friend helpful.

  • 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.