Generating a pdf document using php. Creating a PDF document from a PHP script using the FPDF library



At work I needed to generate a pdf report using php!
Yesterday, having tormented myself with this matter and finally sorted it out, I decided to lay out all my thoughts on this matter, so that it would be stored and not forgotten later, and maybe it would be useful for someone!

So!
Generating something like this is possible using two packages:
1. File_PHP - PEAR package
2. FPDF - something similar, but with a little more functionality, IMHO!

In the end, the second option was chosen!
By the way, if you use 1 package, you will still need a second one, more on that later.
The binding of packages to the script itself is not difficult at all and is as easy as shelling pears! Quite a wide range of functions that allow you to do anything with your pdf!

The problem arises when the need arises to write in Russian letters!
First, you need to convert a TrueType font into a metric font, which is what Adobe uses.
This is done using the program ttf2pt1. You can easily download it on the internet! The program works from the command line! To generate a metric font with the amf extension, type in the command line ttf2pt1 -A font.ttf name of the generated font. A file appears with the extension afm. In my case I was working with the arial font. Therefore the team was like this ttf2pt1 -A arial.ttf arial

PHP:
MakeFont (string fontfile , string afmfile [, string enc [, array patch [, string type ]]])
font>

Where:
fontfile - TrueType font
afmfile - the afm font you generated
enc - encoding (in this case we indicate the Cyrillic alphabet cp1251)
patch - optional encoding change (do not specify)
type - font type (TrueType by default, so you don’t have to specify it)

So, we create a script in which we include the file makefont/makefont.php in a directory, say font, like this:

PHP:
MakeFont ("arial.ttf" , "arial.afm" , "cp1251" ) ;
font>

And let's launch it! After which two files describing the script are generated!
These are arial.php and arial.z
In this case, the key file for our work is arial.php, which contains a lot of interesting things!

We leave this whole thing on the server where our scripts will work!
Using FPDF commands (which can be found in the documentation) we create a pdf file, but in order to connect the fonts we created to it, we need to call the FPDF addfont() function.

Namely like this:

PHP:
$pdf = new FPDF();
$pdf -> addfont ("arial" , "" , "font/arial.php" );
font>

As you already understood, the first argument of the function is the name of the font, the third is the path to the PHP file we generated! The second argument is the font style (bold, italic, etc.). However, to use it, you need to repeat the operations to create the font accordingly for bold, italics, etc.!

We write some Russian text and output it to PDF! And again! We display the Russian font, but it’s ugly! The distance between the letters is different, everything is very crooked and uneven! And all because the arial.php file with a description of the script was somehow generated incorrectly!
Let's see what's in it:
And it contains an array $cw, which looks like key=>value = character=>character size! And if you look closely, for the Latin alphabet there is a different size for each letter, but for the Cyrillic alphabet the same size is 750! You can manually change these dimensions to achieve a beautiful look!

But I’ll probably post the already corrected size chart for arial regular!

Thank you all for your attention!
Sorry for the clumsiness of the presentation!
But I hope the content is useful!

I have a large PDF file that is a floor map for a building. It has layers for all office furniture, including text windows with seat locations.

Is there a way to do this via PHP? (Or even Ruby or Python if that's what's needed)

your original request: "I have a large PDF file that is a floor map for a building."

I'm afraid to tell you that it may be more difficult than you realize.

The reason the last known use of the lib is for pdf parsing is smalot and the problem is known to be with a large file.

Here's also a Lookig for a real php lib to parse pdfs, without the memory spike, which needs php config to disable the memory limit like a lot of "developers" do (which is really not practical in my opinion).

see this post for more information on smalot performance: https://github.com/smalot/pdfparser/issues/163

They will allow you to open a PDF file and add PHP content to it. I'm guessing you could also use your functionality to search through existing content for the values ​​you need.

Another possible library is TCPDF: http://www.tecnick.com/public/code/cp_dpage.php?aiocp_dp=tcpdf

Update to add a more modern library: PDF Parser

Hmm... not exactly php, but you can call a program from php to convert the pdf into a temporary html file, and then parse the resulting file using php. I did something similar for my project and this is the program I used:

What's cool about the program is that it will spit out text elements in tags

with absolute position coordinates. It looks like this is exactly what you are trying to do.

  • Translation

Most web services export data in different formats for further use. This article is about how to export data in pdf format.
Although many people know how to do this, I will describe briefly for those who do not know.

PHP allows us to generate pdf files on the fly. FPDF is a free PHP code that allows you to create documents in pdf format and perform various manipulations with them.

PDFlib
The PHP API contains a large number of functions for working with PDF, implemented based on PDFlib. Despite this, this library is not free for commercial use. The free version is called PDFlib Lite and is free for personal use, but it is limited in functionality. In order to use the full PDFlib library you must purchase a license.

Why FPDF?
An alternative is to use FPDF, a free class containing a large number of functions for creating and manipulating PDF documents. The key word for this moment is that it is free. You can download, use and modify this class as you please. In addition to being free, this library is much simpler than PDFlib. To use PDFlib you need to install it as an extension to PHP, while FPDF can be included directly in the program.

Creating PDF Documents
To get started, you need to download the FPDF code from the FPDF Web site and include it in the program. For example, like this


Below is an example of using the library to generate a simple PDF.
We will create a new FPDF object:

The FPDF constructor accepts the following parameters
  • Page orientation (P or L) portrait or landscape
  • Dimension (pt,mm,cm or in)
  • Document Size (A3, A4, A5, Letter and Legal)
Next we will set some document properties
$pdf->SetAuthor("Lana Kovacevic");
$pdf->SetTitle("FPDF tutorial");

Since in this example we are using the same font for the entire document, we set it before creating the page
$pdf->SetFont("Helvetica","B",20);
$pdf->SetTextColor(50,60,100);

The SetFont function has 3 parameters; font name, style and size. We are using Helvetica, bold and 20 points, we will use this for the title of the document.
You can use any other font using the AddFont function.
Using the SetTextColor function, we set the font color for the entire document. Color can be represented in RGB or gray scale. In this example we are using RGB values.
Now that the main thing is done, let's start creating pages.
$pdf->AddPage("P");
$pdf->SetDisplayMode("real","default");

The AddPage() function can be passed "P" or "L" parameters to specify the page orientation. The SetDisplayMode function determines how the page will be displayed. You can define magnification and layout options. In the example we are using 100% magnification and the default layout defined in the program used for viewing.

Now that we have a page, let's insert an image into it to make the page nicer, and we'll also add a link. We will display the FPDF logo using the Image function and pass the following parameters to it - file name, dimension and address.

$pdf->Image("/logo.png",10,20,33,0," ","http://www.fpdf.org/");

To add a link use the following command
$pdf->Link(10, 20, 33,33, "http://www.fpdf.org/");

Now let's create a header with a frame
$pdf->SetXY(50,20);
$pdf->SetDrawColor(50,60,100);
$pdf->Cell(100,10,"FPDF Tutorial",1,0,"C",0);

The SetXY function sets the x and y coordinates of the point where we want to display the title. SetDrawColor sets the border color using RGB values. After that, we call the Cell function to display a rectangle with our title text. We pass the following parameters to the function: width, height, text, border, ln, alignment and padding. The value of the border is 0 - no border or 1 for the presence of a border. For ln we use the default value of 0, "C" to center the text and 0 for the padding parameter. If we set the last parameter to 1 our rectangle would be filled in, a value of 0 would leave it transparent.
Now we want to write small text into our document
$pdf->SetXY(10,50);
$pdf->SetFontSize(10);
$pdf->Write(5,"Congratulations! You have generated a PDF.");

So again we are setting the x and y coordinates of the text output, but now we will reduce the font size using SetFontSize. The Write function will print the text into our document. Parameter 5 sets the height, it only makes sense when we have many lines in our text.
At the end we output our result using the Output function.
$pdf->Output("example1.pdf","I");

Here we specified the file name and output parameters, in this case "I". The "I" parameter will output the result to the browser.

So the full text:

require("fpdf.php");
//create a FPDF object
$pdf=new FPDF();
//set document properties
$pdf->SetAuthor("Lana Kovacevic");
$pdf->SetTitle("FPDF tutorial");
//set font for the entire document
$pdf->SetFont("Helvetica","B",20);
$pdf->SetTextColor(50,60,100);
//set up a page
$pdf->AddPage("P");
$pdf->SetDisplayMode(real,"default");
//insert an image and make it a link
$pdf->Image("/logo.png",10,20,33,0," ","http://www.fpdf.org/");
//display the title with a border around it
$pdf->SetXY(50,20);
$pdf->SetDrawColor(50,60,100);
$pdf->Cell(100,10,"FPDF Tutorial",1,0,"C",0);
//Set x and y position for the main text, reduce font size and write content
$pdf->SetXY(10,50);
$pdf->SetFontSize(10);
$pdf->Write(5,"Congratulations! You have generated a PDF.");
//Output the document
$pdf->Output("example1.pdf","I");

Now that we have learned how to create documents, let's see what else we can do using FPDF. The example below shows us how to create the top and bottom (header and footer :-)) of our document.

require("fpdf.php");
class PDF extends FPDF
{
function Header()
{
$this->Image("/logo.png",10,8,33);
$this->SetFont("Helvetica","B",15);
$this->SetXY(50, 10);
$this->Cell(0,10,"This is a header",1,0,"C");
}
function Footer()
{
$this->SetXY(100,-15);
$this->SetFont("Helvetica","I",10);
$this->Write(5, "This is a footer");
}
}
$pdf=new PDF();
$pdf->AddPage();
$pdf->Output("example2.pdf","D");

As you can see, we have created a child class using inheritance and creating the Header and Footer functions. We then created a new object and added the page to the document. The AddPage function will automatically call the Header and Footer functions. Finally, we output the resulting information to a file called example2.pdf using the value “D”. In this case, the browser will offer to save this file.

So we've learned the basics of creating PDF documents, for more details use

Sooner or later the question of generating PDF files arises. It is convenient and the pages can be made quite beautiful. There are many different libraries for PHP, in this case I had the task of making it in FPDF. This library, or rather the class, is distributed free of charge and can work with different types of encodings, including CP1251. Probably the disadvantage of this library is the lack of UTF support, but there is a separate patched UFPDF library, I will not consider it.

You probably ask why the pain with the Cyrillic alphabet? Let's just say that I spent a lot of time looking for how to get Russian text to show instead of scribbles. I did everything according to manuals from official sources.
So, in order for there to be Russian text, we need fonts, I used Arial, Times New Roman, Verdana. Create a fonts folder in your project. Place the fonts you need there. Now we need to convert them to FPDF. Many sites suggest using a special utility ttf2pt1.

Ttf2pt1 -a arial.ttf arial Once saved, let’s check it in the browser. It creates 2 files, then you need to create a php file and do the following, or rather, it will create a php file that contains information about the font. Don't forget to set permissions on the folder where you will generate fonts.

I have done all this more than once. And the script didn’t want to work. After which I found an easier way to convert fonts.
Let's go http://fpdf.fruit-lab.de/index.php?id=3 to this site. Select the encoding cp1251, then attach the font we need and click Convert. There we will be interested in php, afm, z. Download these files to the fonts folder we created. Next you need to rename the .php.txt file to .php.
Then we will open this php file (from the site we download it as .php.txt and then rename it). In this case, we will be interested in the font name ($name="ArialMT";). Now we have a font and a font name. You can start creating the PDF generator itself. We create the file we need, connect the necessary libraries.

Define("FPDF_FONTPATH", __system_directory__ ."API/font/"); // just in case, I wrote the full path to the library. require("/usr/share/php/fpdf/fpdf.php"); // declare the class and class constructor, in this case I have a landscape sheet $pdf=new FPDF("L"); //you need to connect the font by specifying the font name and file name. $pdf->AddFont("ArialMT","","119379869a251bdd6a14438b3c5514f2_arial.php"); $pdf->AddPage(); // select the font for the text. $pdf->SetFont("ArialMT","",35); $pdf->Cell(40,10,"Russian text!"); $pdf->Output();

I spent most of my time due to an error that occurred: “FPDF error: Undefined font: arialmt B.” It was probably caused by incorrect font conversion when using MakeFont or using an incorrect parameter, for example, an error occurs when parameter 2 does not match SetFont or vice versa.

// Error in this example:
$pdf->AddFont("ArialMT","","119379869a251bdd6a14438b3c5514f2_arial.php"); $pdf->SetFont("ArialMT","B",35); //And this one too: $pdf->AddFont("ArialMT","B","119379869a251bdd6a14438b3c5514f2_arial.php"); $pdf->SetFont("ArialMT","",35); //works $pdf->AddFont("ArialMT","B","119379869a251bdd6a14438b3c5514f2_arial.php"); $pdf->SetFont("ArialMT","B",35);

As it turned out, the errors were out of nowhere, but I’m glad that I sorted them out, and I hope that this little article will help me not waste time searching for problems related to encodings.


Business card website: features of a good start
Air mattresses from Lamon
WebNames.Ru – a decade of activity on the Internet
Apartment for your site.
Technologies from BoldSoft
How to succeed in hopeless projects
New type of navigation system for page display
Generating PDF using PHP
PHP and PostgreSQL
Optimizing MySQL

Generating PDF using PHP

Preface
One of the reasons why I love PHP- this is because it constantly provides support for new technologies. The language is easily extensible, and developers can easily add new modules to it, so PHP has become one of the most functional Web languages ​​with support for a huge variety of different technologies. Extensions available today allow developers to easily work with an IMAP and POP3 server; dynamically create images and drawings in Flash format; perform credit card verification operations; encrypt sensitive data; and work with XML databases.

And that is not all! One of the most interesting extensions added to date in PHP- this is an extension PDFLib, which allows developers to dynamically generate documents in the format PDF (Adobe Portable Document Format). Over the next few pages, I will briefly talk about this module, and give an overview of the functions used, and tell you how to use this extension in PHP development. So let's go!

Go!
To enable the extension PDFLib, first you need to install the appropriate library on your system. If you work for Linux, you can download a copy from http://www.pdflib.com/pdflib/index.html and compile it for your server. If you work on Windows, everything is much simpler - along with the distribution PHP a compiled module is already supplied PDF, and all you need to do is activate it by uncommenting the corresponding line in the configuration file.

In addition, you will need a copy of the program Adobe Acrobat PDF reader to read documents created using the library PDFLib. You can download Adobe Acrobat Reader for free from the manufacturer’s website: http://www.adobe.com/

Once everything is installed, it's time to create a simple PDF document:

Save this file and then open it in your browser. PHP will process this script and generate a new one PDF file that will be saved in the location specified at the top of the script. This is what you will see when you open this PDF document:

All rights to publish this article belong to

Anatomy lesson
Let's take a closer look at the code used in the example above.

Creation PDF file in PHP involves 4 basic steps: creating an index to the document, registering fonts and colors for the document, writing or drawing to the index using predefined functions, and saving the document.

Let's start with the first step - creating a pointer to PDF

// create handle for new PDF document $pdf = pdf_new();

This is achieved using the pdf_new() function, which returns a pointer to this document. This pointer is then used in all subsequent creation operations. PDF document.

The next step is to give PDF file name - this is achieved by the pdf_open_file() function, which takes two arguments - the pointer returned by the previous function and the actual file name, defined by the user.

// open a file pdf_open_file($pdf, "philosophy.pdf");

Once the document has been created, the beginning of a new page can be inserted into it using the pdf_begin_page() function,

// start a new page (A4) pdf_begin_page($pdf, 595, 842);

and the end of the page - yes you guessed it!! - function pdf_end_page().

// end page pdf_end_page($pdf);

Note that the pdf_begin_page() function requires two additional parameters, which represent the width and height of the generated document in pixels (a pixel is 1/72 of an inch). If you are bad at math, a textbook on PHP includes standard sizes for all common page sizes, including A4, which is used above.

Between the calls pdf_begin_page() and pdf_end_page() there is code that writes to a file, whether it be text, pictures or geometric shapes. In this example, I'm just writing a line of text into the document - so all I need to do is select a font and use it when writing text into the document.

Font selection and registration is performed by the pdf_findfont() and pdf_setfont() functions. The pdf_findfont() function selects a font to use in the document, and requires the font name, encoding method, and a Boolean parameter indicating whether the font should be embedded in the document. PDF document; and it returns a font object, which can then be used when calling the pdf_setfont() function.

$arial = pdf_findfont($pdf, "Arial", "host", 1); pdf_setfont($pdf, $arial, 10); Once the font is selected, the pdf_show_xy() function can be used to write text to a specific location on the page.
// print text pdf_show_xy($pdf, "There are more things in heaven and earth, Horatio,", 50, 750); pdf_show_xy($pdf, "than are dreamed of in your philosophy", 50, 730);

As you noticed, this function requires a pointer to PDF document, a link to the font object used, the text to be written and the X Y coordinates of the place from where to start writing the text. These coordinates are specified relative to the point (0,0), which is located in the lower left corner of the document.

Once the text has been written, the page is closed by calling the pdf_end_page() function. You can then add more pages or, as I did here, simply close the document using pdf_close(). This function will save the document with the name specified when calling pdf_open_file() and destroy the document pointer.

All rights to publish this article belong to

And here is the PDF output:

All the magic here lies in the pdf_open_image_file() and pdf_place_image() functions. The first one takes the image type - GIF, JPEG, TIFF or PNG- and the file name as arguments, and returns a pointer to the drawing, which can then be reused in the document.

The pointer to the image returned above can then be passed to the pdf_place_image() function, which will place the image at a specific location on the page. The coordinates passed to this function (the second and third arguments) refer to the lower left corner of the picture, and the fourth argument specifies the scaling parameter of the picture when displayed (1 - will show the picture at 100% scale, 0.5 will reduce it by half.)

All rights to publish this article belong to

Shortest distance between two points
Let's not stop! Module PDF includes a huge number of functions that will help you draw lines, circles and other shapes. Here's an example where we'll draw a line.

Here's what you'll see:

In this case, the process of drawing a line involves using the pdf_moveto(), pdf_lineto() and pdf_stroke() functions.

In the example above, I'm drawing a line from point (20,780) to point (575, 780). To do this, I first need to place the cursor at the starting point (20,780) by calling the to pdf_moveto() function.

Then you need to set the endpoint using pdf_lineto():

Finally, we draw a line using pdf_stroke().

The line color is set by the pdf_setcolor() function, which takes several parameters: a pointer to PDF document, the line type: "stroke", "fill" or "both", the color palette (RGB or CMYK), and a list of color values ​​that match the selected palette.

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

It is important to note that the list of color values ​​passed to pdf_setcolor() must be specified as a percentage intensity value - that is, the intensity of a given color expressed as a percentage of the maximum possible. For example, if I want to set (RGB: 255,0,0) as the fill color, my pdf_setcolor() function call would look like this,

pdf_setcolor($pdf, "stroke", "rgb", 1, 0, 0);

And the yellow fill will look like this:

pdf_setcolor($pdf, "fill", "rgb", 1, 1, 0);

All rights to publish this article belong to

Square peg, round hole
Lines aren't the only things you can draw - circles and rectangles are also on today's menu. Look at the example below:

Here's the output:

In this case, the pdf_rect() function is used to draw a rectangle using the given coordinates of the lower left corner, height and width. The rectangle is then filled and stroked with two different colors using the pdf_fill_stroke() function.

pdf_setcolor($pdf, "fill", "rgb", 1, 1, 0); pdf_setcolor($pdf, "stroke", "rgb", 0, 0, 0); pdf_rect($pdf, 50, 500, 200, 300); pdf_fill_stroke($pdf);

Circles are drawn by the pdf_circle() function, which takes three arguments: the X and Y coordinates of the circle's center and the length of the radius.

pdf_circle($pdf, 400, 600, 100);

This ability to draw geometric images on the fly can come in handy in a variety of situations. For example, here is one of them - in it, a couple of "for" loops are connected to the pdf_lineto() function to generate a grid of lines.

Here's the output:

All rights to publish this article belong to

And now, when viewing the document in Adobe Reader, you will be able to see this information in the Document Properties.

All rights to publish this article belong to

Piece of Pie
Now that you know how to create documents PDF, let's turn to real application. The following example demonstrates how PHP can take numerical data and generate graphs from them - for example, a multi-color pie graph.

The form below asks for several pieces of data, in the form of numbers separated by commas. After entering a few numbers, the "pie.php" script converts them from absolute numbers into pieces of data of relative sizes and uses these pieces to generate PDF document containing a pie chart, highlighting different pieces and filling them with different colors.

Pie Chart Generator

Enter numeric values ​​(pie segments), separated by commas
And here is the script:

The data entered into the form is passed to the "pie.php" script in the $data variable; this data is then split into its individual components by explode(), and each value is assigned to the $slices array. The loop then converts these numbers into degrees for the circle and draws an arc for each piece. Each pass of the loop also calculates the coordinate of the end point of the arc and draws a line segment to separate the arc from the rest of the circle. Once the piece of pie is drawn, the pdf_fill_stroke() function is used to fill it with color; the color is taken from the $colours array.

We will not consider how the script calculates the length of each arc and line segment - everything is explained in the code comments.

If you enter 5 equal pieces of data, the graph will look like this,

If you enter 2, then:

That's it - play with the script and see how the different pieces change shape to reflect the relative sizes of the data. Until then - see you soon!

Note: All examples in this article have been tested on the platform Linux/i586 with Apache 1.3.12 and PHP 4.2.0. Examples are provided for illustrative purposes only and are not intended for real-life applications.







2024 gtavrl.ru.