Building PDF Documents with PHP 5

PHP is a versatile language with some surprising capabilities. It can even create PDF documents on the fly, with the right third-party PDF library. If you can’t imagine why you’d want to do that, think about the various formats used by applications when retrieving data from databases — and keep reading.

Introduction

As the enthusiastic PHP programmer that you surely are, you’ll certainly know that this mature server-side scripting language can be used in all sorts of clever ways to develop a huge variety of applications, including form validation systems, full-featured database abstraction layers, powerful error loggers, and so forth. And certainly, the list goes on and on.

The flexibility and versatility offered by PHP is remarkable when it comes to building applications that will be used for different website development purposes. However, it isn’t my intention here to enumerate the thorough advantages of PHP. 

Nonetheless, there’s one thing that I’d like to stress here with reference to the robust capabilities offered by PHP. As you probably heard, this powerful server-side scripting language has the venerable capacity (yes, that’s the right adjective) for dynamically building PDF documents. This feature makes it suitable for use with web applications that deliver database contents in PDF files. 

Of course, the ability to create PHP documents on the fly comes at a cost. PHP 5 currently doesn’t support this feature natively, which means that you’ll need to download a third-party PDF library to start generating PDF files quickly. PHP’s official web site recommends the use of the popular PDFlib package, which offers support for multiple programming languages, such as Python, Perl, and naturally PHP. The down side to using this library is that you’ll have to pay a license to use it commercially.

If you prefer, you can use an streamlined version of the PDFlib package, called “PDFlite,” but it lacks some important features which are present in the commercial version. In either case, you may want to first download this library (or another one of your choice), and then install it on your on testing server, and finally get started with building basic PDF documents directly from your PHP scripts.

So, if creating dynamic PDF files with PHP 5 is an interesting topic to you, keep reading. In this series of articles I’ll show you how to start using the “PDFlib” package to build basic PDF documents. In upcoming articles I’ll cover other important characteristics, like including images into a PDF file, displaying blocks of text, and drawing basic shapes.

Let’s not waste any more time in preliminaries. Click on the link below to start learning how to build dynamic PDF documents with PHP 5. Let’s begin now!

{mospagebreak title=Building basic PDF documents with PHP 5 using an object-oriented approach}

As I stated in the beginning of this article, building basic PDF files with PHP 5 is a straightforward process that can be easily learned even if you’re a novice PHP programmer. In simple terms, and assuming the corresponding PDFlib library has already been installed on your web server, creating a simple PDF document is reduced to spawning an instance of a bundled class, called “PDFlib”, and using some of its most common methods. Period.

But let me dispose of the theory for an instant and show you this process from a practical point of view. Take a look at the following code sample. It first creates a primitive PDF file that contains a basic text, and then displays this content by using a default PDF application:

// example creating a basic PDF (A4) document with PHP

 

try {

// create new instance of the ‘PDFlib’ class

$pdf=new PDFlib();

// open new PDF file

if(!$pdf->begin_document("","")){

throw new PDFlibException("Error creating PDF document. ".$pdf-
>get_errmsg());

}

  $pdf->set_info("Creator","pdf_example.php");

  $pdf->set_info("Author","Alejandro Gervasio");

$pdf->set_info("Title","Example on using PHP to create PDF
docs");


  $pdf->begin_page_ext(595,842,"");

 

  $font=$pdf->load_font("Helvetica-Bold","winansi","");


  $pdf->setfont($font,24.0);

  $pdf->set_text_pos(50,800);

  $pdf->show("PHP is great for creating PDF documents!");

// end page

  $pdf->end_page_ext("");

 

// end document

  $pdf->end_document("");


// get buffer contents

  $buffer=$pdf->get_buffer();

// get length of buffer

  $len=strlen($buffer);

// display PDF document

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

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

   header("Content-Disposition: inline; filename=example.pdf");

 echo $buffer;

}

  catch (PDFlibException $e){

   echo ‘Error Number:’.$e->get_errnum()."n";

   echo ‘Error Message:’.$e->get_errmsg();

    exit();

}

As you can see in the above example, I first created a new instance of the aforementioned “PDFlib” class, and then used its “begin_document()” method to start an empty PDF document, which for now resides on the web server’s memory. Next, I specified some basic information, like the document’s title and author, and after that I utilized the “begin_page_ext()” method to specify the dimensions of the page that will be used (in this case, I’m using an A4 page).

Still with me? All right, the next thing that the previous example does is call in the proper sequence the “set_font()” and “set_text_pos()” methods to specify what font type should be used to include text into the page, and the X, Y coordinates where the text in question should be displayed.

Also, the previous script uses the “show()” method to display a basic string on the PDF page. Then it closes the page and the document respectively, via the respective “end_page_ext()” and “end_document()” methods.

Lastly, the script finishes its execution by echoing the buffer contents in PDF format via the corresponding HTTP headers. Quite simple, right?

At this point you hopefully have grasped the logic that stands behind building basic PDF files with PHP 5. In simple words, you’ll always have to create an instance of the “PDFlib” class that you learned before, then open a new document and a new page (this is only applicable when using certain methods), and finally include some type of content into it, such as texts, images, etc. At the end of this procedure, the respective page and documents must be closed, and the contents of the buffer have to be displayed via the appropriate HTTP headers.

To complement the previous explanation, below I included an illustrative screen shot that shows the output generated by the previous script. Here it is:

So far, so good, right? At this stage you learned the basics of creating some simple PDF files with PHP 5, so I think it’s time to develop another practical example. This will help you acquire a more solid background in how to work with PDF documents from your PHP 5 scripts.

In the next section I’ll show you how to use some of the methods that you saw earlier to create A3 documents in PDF format. Want to see how this will be done? All right, click on the link below and keep reading.

{mospagebreak title=Working with different page sizes}

In the previous section, you hopefully learned how to build an A4 PDF document by using some methods that come integrated with the already familiar “PDFlib” package. I’m going to develop yet another practical example, this time to create an A3 document, which also will contain some basic text.

The corresponding code sample is as follows:

// example creating a basic A3 PDF document with PHP 5

try {

// create new instance of the ‘PDFlib’ class

$pdf=new PDFlib();

// open new PDF file

if(!$pdf->begin_document("","")){

throw new PDFlibException("Error creating PDF document. ".$pdf-
>get_errmsg());

}

  $pdf->set_info("Creator","example.php");

  $pdf->set_info("Author","Alejandro Gervasio");

$pdf->set_info("Title","Example on using PHP to create PDF
docs");

  $pdf->begin_page_ext(842,1190,"");

 

   $font=$pdf->load_font("Helvetica-Bold","winansi","");

  $pdf->setfont($font,24.0);

  $pdf->set_text_pos(50,800);

  $pdf->show("PHP is great for creating PDF documents!");

// end page

  $pdf->end_page_ext("");

 

// end document

  $pdf->end_document("");

// get buffer contents

    $buffer=$pdf->get_buffer();

// get length of buffer

  $len=strlen($buffer);

// display PDF document

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

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

  header("Content-Disposition: inline; filename=example.pdf");

   echo $buffer;

}

catch (PDFlibException $e){

  echo ‘Error Number:’.$e->get_errnum()."n";

  echo ‘Error Message:’.$e->get_errmsg();

  exit();

}

As you can see, building A3 PDF documents with PHP 5 doesn’t differ too much from creating one that has an A4 format. The above script, which is responsible for constructing the document, uses the same methods that you learned in the previous section, but in this case the “begin_page_ext()” method specifies that the document being created should fit the A3 format, that is 842px X 1190px respectively.

In addition, to complete the above explanation, I included an image (actually, its real size has been changed for editing reasons) that shows the output generated by the previous script:

All right, after studying the previous example, you’ll have to agree with me that building some basic PDF files with PHP 5 is indeed a no-brainer process that can be tackled with minor problems. As you saw, the procedure is reduced to spawning an instance of the corresponding “PDFlib” class, and then calling some of its numerous methods, depending on what kind of content you want to include into the file.

Assuming that you grasped how the previous example works, in the last section of this tutorial I’m going to provide you with an additional code sample, which will show you how to create the same PDF document that you saw earlier, but this time in A5 format.

To see how this last example will be developed, jump ahead and read the next few lines.

{mospagebreak title=Creating a basic A5 PDF document using PHP 5}

As I said in the section that you just read, the last code sample that I’m going to provide you in this tutorial is aimed at illustrating how to build a primitive PDF file with PHP 5, which will be rendered in A5 format. As you might guess, the document can be easily constructed by utilizing the same set of methods that you saw in the previous example, but in this case, the “begin_page_ext()” method indicates that the document to be created must fit the A5 format.

Having explained that, here’s the respective code sample:

// example creating a basic A5 PDF document with PHP 5

  try {

// create new instance of the ‘PDFlib’ class

  $pdf=new PDFlib();

// open new PDF file

  if(!$pdf->begin_document("","")){

throw new PDFlibException("Error creating PDF document. ".$pdf-
>get_errmsg());

}

  $pdf->set_info("Creator","example.php");

  $pdf->set_info("Author","Alejandro Gervasio");

$pdf->set_info("Title","Example on using PHP to create PDF
docs");

  $pdf->begin_page_ext(421,595,"");

 

     $font=$pdf->load_font("Helvetica-Bold","winansi","");

  $pdf->setfont($font,24.0);

  $pdf->set_text_pos(50,500);

  $pdf->show("PHP is great for creating PDFs!");

// end page

  $pdf->end_page_ext("");

 

// end document

  $pdf->end_document("");

// get buffer contents

   $buffer=$pdf->get_buffer();

// get length of buffer

    $len=strlen($buffer);

// display PDF document

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

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

  header("Content-Disposition: inline; filename=example.pdf");

   echo $buffer;

}

catch (PDFlibException $e){

  echo ‘Error Number:’.$e->get_errnum()."n";

  echo ‘Error Message:’.$e->get_errmsg();

  exit();

}

I’m not going to spend much time explaining how the above example works, since it looks very similar to the ones that you learned in earlier sections of this article. The only detail to stress here is with reference to the use of the ““begin_page_ext()” method, which instructs the script to build a page whose dimensions must fit the A5 format.

Below I included another screen shot that shows very clearly how the previous PDF file is outputted to the computer system:

That’s all for the moment. Hopefully, all of the code samples shown in this tutorial will serve to get you started building some basic PDF files in PHP 5 with minor hassles. Happy coding!

Final thoughts

In this first tutorial of the series I walked you through using some basic methods that come bundled with the “PDFlib” library to build a few basic PDF documents using PHP 5. As you learned from all the code samples shown here, the process is quite simple to grasp. Many of these methods are very intuitive, particularly when it comes to creating PDF files that contain only basic text.

In the next part of the series, I’m going to teach you how to build PDF files that include multiple lines of text, directly from your PHP 5 scripts, among other useful things. Now that you’ve been warned, you won’t want to miss it!

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort