Home  >  Article  >  Backend Development  >  How to write a PDF document generator in PHP

How to write a PDF document generator in PHP

WBOY
WBOYOriginal
2016-08-08 09:33:32952browse

How to write a PDF document generator in PHP

One of the biggest advantages of PHP is that it is very easy to support new technologies. The extensibility of this language allows developers to easily add new modules, and the support of technical groups around the world and the support of many extension modules make PHP It has become one of the most full-featured web programming languages. Extension modules currently available enable 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. Now, there is a new module that can be bound to PHP, that is, the PDFLib extension module, which allows developers to dynamically generate files in PDF (Adobe Portable Document Format) format. Let's take a look at it first. See how to use this module in PHP.

In order to enable PHP to operate PDF format documents, you must first install the PDFLib extension library in your system. If you are using a Lunix system, you can download it from http://www.pdflib.com/pdflib/index. html and compile it. If you are using a Windows system, it is even simpler. You only need to download a compiled PDFLib library, and then remove the comments of the corresponding lines in the PHP configuration file.


extension=php_pdf.dll


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


dl("php_pdf.dll");


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

Once you have done the preliminary preparation, you can create the PDF file. Here is 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 the font object

$arial = PDF_findfont($pdf, "Arial", "host", 1);

PDF_setfont($pdf, $arial, 10);


//output text

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

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


//End page

PDF_end_page($pdf);


// Close and save file

PDF_close($pdf);

?>

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

Now let's analyze the 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. Use the functions provided by PDFLib to write text or draw pictures to the file handle; 4. Save the document.

First, create a PDF document handle with the following syntax:


$pdf = PDF_new();


This task is completed by the PDF_new() function, which returns a handle to the PDF document, which 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 previously created file handle and a custom file name as parameters:


PDF_open_file($pdf, "PDFTest.pdf");


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


PDF_begin_page($pdf, 595, 842);


Then end the page with PDF_end_page().

Note here that in the PDF_begin_page() function, there are two other parameters. They represent the width and height of the page size respectively. The unit is points (point, 1 point is equal to 1/72 inch). Maybe mathematics is not your strong point here. , PHP also provides most standard page sizes, such as A4, etc. The above example uses the A4 size.

The code between calling the PDF_begin_page() function and the PDF_end_page() function writes content to the PDF document. The content can be text, images, geometric figures, etc. In the example, we just write a line of text, first get a font, and then write the text into the document. It is very convenient to select and register fonts through the PDF_findfont() and PDF_setfont() functions. The PDF_findfont() function prepares a font to be used in the document. The required parameters include the name of the font, the encoding used, and whether the font should be embedded in in PDF file. The PDF_findfont() function returns a font object, which 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 a string to a specified location on the page.


PDF_show_xy($pdf, "This is an 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. The last two parameters are the coordinate positions of the string to be written. Note that the origin of the coordinates (0, 0) is at the lower left corner of the document. Once the text is finished, the page can be closed with PDF_end_page(), and of course you can write more pages. After all pages are written, use the PDF_close() function to close the document. At this time, the document will be saved to the file name and path specified when calling the PDF_open_file() function, and the document handle will be destroyed.

The PDFLib library can do more than that. You can also add images to the page. Let's take the previous file as an example and add an image file below the text. The following statement implements the image adding function:


$image = PDF_open_image_file($pdf, "jpeg", "PDFImageTest.jpg");

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


Is not it simple? The PDF_open_image_file() function opens a graphics file. Acceptable image types are: GIF, JPEG, TIFF and PNG. This function returns the image handle. The PDF_place_image() function uses the previous image handle to insert the image into the PDF document. middle. 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 means it is displayed as the actual size, and 0.5 means it is displayed at half the original size.

In addition to drawing existing images in PDF documents, the PDF module also provides many functions that allow us to draw geometric figures. For example: geometric patterns such as straight lines, circles, rectangles, etc. Here is how to draw a straight line:


$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 the straight line

PDF_setcolor($pdf, "stroke", "rgb", 0, 0, 0);


//Place a logo 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 straight line under the Logo

PDF_moveto($pdf, 20, 780);

PDF_lineto($pdf, 575, 780);

PDF_stroke($pdf);


//Draw another straight 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 can be seen from the above example, to draw a straight line, only three functions are needed: PDF_moveto(), PDF_lineto() and PDF_stroke(). The above example is to first use the PDF_moveto($pdf, 20, 780) function to move the cursor to the coordinate (20, 780), and then use the PDF_lineto($pdf, 575, 780) function to define the coordinates of another point on the straight line (575, 780), and finally use PDF_stroke($pdf) to draw the line. The function PDF_setcolor($pdf, "stroke", "rgb", 0, 0, 0) that sets the color has several parameters. The color fill mode has three options: stroke, fill, and both. The color can be RGB or CMYK. The color values ​​of the color scheme. It is worth noting that the value used in the PDF_setcolor() function is the percentage of the color, which 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), if you want to set it to yellow, you can do this: PDF_setcolor($pdf, "stroke", "rgb", 1, 1, 0).


To draw filled rectangles and circles, 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 next four parameters are the coordinates X, Y, width and height of the lower left corner.

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 a circle, the parameters are the center coordinates and the radius of the circle.


PDF_circle($pdf, 400, 600, 100)


In addition, PDFLib also provides functions for writing document summary information. These functions start with PDF_set_info_*(). This information can include: document author, title, content, subject, etc. Here are a few commonly used 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 above in the menu "File" - "Document Properties" - "Summary".

Having said this, I believe everyone has a basic understanding of how to use PDFLib to create PDF documents. Below, we will take a practical example to see how it can serve our work. This example is to generate a pie chart based on the provided data. First, create a data input form and enter the size of each piece in the pie chart. The files are as follows:


Use PHP to create PDF documents (pie charts)

Pie Chart Generator

Please enter the data value of each piece in the pie chart, separated by (,):


Below is the code for the pie.php file:


//Accept 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 in 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 into the corresponding percentage (360-degree circle)

for ($y=0; $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

{

//Set fill color

PDF_setcolor($pdf, "fill", "rgb", $colours[$z][0],

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


// Calculate the end point coordinates of each arc

$end_x = round(250 + ($radius * cos($last_angle*pi()/180)));

$end_y = round(250 + ($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 the arc

PDF_arc($pdf, 250, 250, $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 outer circle outline

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 different values, and you will get different pie charts.

PDFLib is a module with good compatibility. You can not only write it in PHP, but 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; the supported platforms are not only Windows, but also Unix/linux, Mac OS, IBM eServer iSeries 400 and zSeries S/390, etc. Please feel free to ask for the specific operating environment. Visit their website for the latest information.

The above introduces how to use PHP to write a PDF document generator, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn