Generate PDF Documents with PHP on the Windows Platform

If you’re a PHP programmer who has tried to generate PDF documents on the Windows platform, you may have run into some very irritating issues. This article will discuss those issues, show you how to generate PDF documents that can be viewed on a desktop and through a browser, and help you troubleshoot if you run into problems.

Try Googling for "generate pdf with php." You can probably find hundreds of articles with many sample codes here and there.

However, if you try these sample codes on a Windows platform, you will most likely get the following error:


"PHP Fatal error: Uncaught exception ‘PDFlibException’ with message ‘Metrics data for font ‘Arial’ not found’. "

So where and how do you specify this "Metrics data for font" that is required to generate the PDF documents with PHP on Windows?

Setting up the PDF library

Before you can generate PDF documents, first you need to make sure the php_pdf.dll containing the PDFLib library is properly set up.

You can find a copy of php_pdf.dll in the download area of the official PHP web site.

If you are running a thread-safe version of PHP, download the “PECL 5.2.5 Win32 binaries” file. If you are running a non thread-safe version of PHP, download the “PECL 5.2.5 Non-thread-safe Win32 binaries” file. If you do not know whether your PHP is thread-safe or non thread-safe, just try one of these first. If it doesn’t work, try the other.

Unzip the file to a folder. You will find a lot of dlls in there. You only need one of these — the php_pdf.dll. Copy just that file to the “ext” folder where you have installed your PHP.

Next open up php.ini in your favorite editor and add the following line:


extension=php_pdf.dll


Now we are ready to generate pdf documents using PHP on Windows.

Notes on the different versions of php_pdf.dll

One of the major problems people face is that there are so many different versions of php_pdf.dll floating around on the Internet. Also, different people are running different versions of PHP on their servers. On top of this, there are the thread-safe and non thread-safe compilations of PHP and the dll. The two need to match.

This is complicated by the fact that the PDFLib library is now maintained by PDFlib GmbH. While the library is free for testing and developing purposes, you need to purchase a license for commercial use. If you go to PDFlib GmbH, you can see that the latest version of PDFLib is now version 7. However, the php_pdf.dll available from the official PHP site is still version 5.

This partly explains why many of the sample codes you found on the Internet and the official PHP site do not work. Those examples might work on Linux, as it is easy for Linux users to recompile PHP with the latest pdf library. But they might not work on Windows, as most of the available php_pdf.dll is relatively outdated.

{mospagebreak title=Hello world PDF}

As with any other programming language, the best way to start exploring the PHP PDF library is a hello world example.

First, we create a new pdf document named "helloworld.pdf":


$pdf = pdf_new();

pdf_open_file($pdf, ‘helloworld.pdf’);


Then we start a new page:


pdf_begin_page($pdf, 612, 792); // Letter size


In case you are wondering why we’re using the strange numbers of 612 and 792, these are the dimensions for a letter size paper. A letter size paper is 8.5” by 11”. The 612 is obtained by 8.5 * 72. Similarly, 11 * 72 = 792. Hence the two numbers.

If you need to produce an A4-size pdf document, use:


pdf_begin_page($pdf, 595, 842); // A4 size


An A4-size paper is 210mm x 297mm, which is 8.27” by 11.69”. Multiply these by 72, and you get 595 by 842.

After we have created a new page, before we can start printing any text on the new page, we need to set up the font first.

pdf_set_parameter($pdf, ‘FontOutline’,

‘Arial=c:windowsfontsarial.ttf’);

$font = pdf_findfont($pdf, "Arial", "host", 1);

pdf_setfont($pdf, $font, 48);


We are now ready to print “hello world” on the page:


pdf_show_xy($pdf, "hello world, PDF!", 50, 680);


And we wrap up the pdf document with:


pdf_end_page($pdf);

pdf_close($pdf);

pdf_delete($pdf);


Below is the complete code. Copy the code below and save it in a file, say helloworld_pdf.php.


<?php

# helloworld_pdf


// create a new pdf document

$pdf = pdf_new();

pdf_open_file($pdf, ‘helloworld.pdf’);


// start a new page (Letter size)

pdf_begin_page($pdf, 612, 792); // Letter size


// setup font and print hello world

pdf_set_parameter($pdf, ‘FontOutline’,

‘Arial=c:windowsfontsarial.ttf’);

$font = pdf_findfont($pdf, "Arial", "host", 1);

pdf_setfont($pdf, $font, 48);

pdf_show_xy($pdf, "hello world, PDF!", 50, 680);


// done

pdf_end_page($pdf);

pdf_close($pdf);

pdf_delete($pdf);


echo "helloworld.pdf has been generatedn";

?>


To run the code above, open a command window and cd to the directory where you saved the script. Suppose you have installed your PHP in c:php, and you have saved the script as helloworld_pdf.php. From the command prompt, type


c:phpphp helloworld_pdf.php


You should now have a new file named “helloworld.pdf” created in the folder where you run the script.

Double click the pdf file. You will see the pdf document as shown below.




Specifying the font information

The most important line in this example is:


pdf_set_parameter($pdf, ‘FontOutline’, ‘Arial=c:windowsfontsarial.ttf’);


This is the "magic" line that specifies the font information. This is also the line that will fix the following error which many people have encountered:


"PHP Fatal error:” Uncaught exception ‘PDFlibException’ with message ‘Metrics data for font ‘Arial’ not found’ "


You can select any Windows truetype fonts on your system. For example, if you want to use Times New Roman Bold Italic, replace the codes with:


pdf_set_parameter($pdf, ‘FontOutline’, ‘ Times New Roman Bold Italic =c:windowsfontsTIMESI.TTF’);

$font = pdf_findfont($pdf, "Times New Roman Bold Italic", "host", 1);


Run the script again, and you will get the following PDF document:



{mospagebreak title=Finding the filename of the truetype font}

In case you do not know the filename of the respective truetype fonts, just open up your fonts folder in the explorer (usually it’s c:windowsfonts) and choose View – Details. You will see something similar to the following:



The first column shows the descriptive font name, and the second column gives you the filename of the true type font.

Specifying two or more fonts

You can set up two or more fonts with multiple statements of pdf_set_parameter():


pdf_set_parameter($pdf, ‘FontOutline’, ‘Arial=c:windowsfontsarial.ttf’);

pdf_set_parameter($pdf, ‘FontOutline’, ‘Times New Roman=c:windowsfontstimes.ttf’);

pdf_set_parameter($pdf, ‘FontOutline’, ‘Verdana=c:windowsfontsverdana.ttf’);


followed by:


$font1 = pdf_findfont($pdf, "Arial", "host", 1);

$font2 = pdf_findfont($pdf, "Times New Roman", "host", 1);

$font3 = pdf_findfont($pdf, "Verdana", "host", 1);


Below is a complete sample code that will produce the following PDF document:




<?php

# pdf_example2.php


// create a new pdf document

$pdf = pdf_new();

pdf_open_file($pdf, ‘pdf_example2.pdf’);


// start a new page (Letter size)

pdf_begin_page($pdf, 612, 792);


// setup font

pdf_set_parameter($pdf, ‘FontOutline’,

‘Arial=c:windowsfontsarial.ttf’);

pdf_set_parameter($pdf, ‘FontOutline’, ‘Times New Roman=c:windowsfontstimes.ttf’);

pdf_set_parameter($pdf, ‘FontOutline’,

‘Verdana=c:windowsfontsverdana.ttf’);


$font1 = pdf_findfont($pdf, "Arial", "host", 1);

$font2 = pdf_findfont($pdf, "Times New Roman", "host", 1);

$font3 = pdf_findfont($pdf, "Verdana", "host", 1);


pdf_setfont($pdf, $font1, 20);

pdf_show_xy($pdf, "This is Arial at 20 pt.", 50, 680);


pdf_setfont($pdf, $font2, 24);

PDF_continue_text($pdf, "This is Times New Roman at 24 pt.");


pdf_setfont($pdf, $font3, 36);

PDF_continue_text($pdf, "This is Verdana at 36 pt.");


// done

pdf_end_page($pdf);

pdf_close($pdf);

pdf_delete($pdf);

echo "pdf_example2.pdf has been generatedn";


?>


{mospagebreak title=Generating PDF documents for browsers}

Now that we are able to generate PDF documents through the command prompt, let us move on to generate PDF documents for browsers.

Copy the code below and save it in a file on your web server.


<?php

# pdf_example3

# for the browser


// create a new pdf document

$pdf = pdf_new();

$filename = ‘c:pdf_example3.pdf';

pdf_open_file($pdf, $filename);


// start a new page (Letter size)

pdf_begin_page($pdf, 612, 792);


// setup font and print hello world

pdf_set_parameter($pdf, ‘FontOutline’,

‘Arial=c:windowsfontsarial.ttf’);

$font = pdf_findfont($pdf, "Arial", "host", 1);

pdf_setfont($pdf, $font, 24);

pdf_show_xy($pdf, "pdf_example3 for the browser", 50, 680);


// done

pdf_end_page($pdf);

pdf_close($pdf);

pdf_delete($pdf);


// send it to browser

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

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

readfile($filename);

unlink($filename);

?>


You will find that the first part of the code is exactly the same as the command line version of the hello world example.

Once the PDF file is generated, all we need to do is to push the content to the browser:


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

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

readfile($filename);


Note that the pdf file ‘c: pdf_example3.pdf ‘ is a temporary one. You can save this in any directory you want. Just make sure that the web server has write permission to that directory. Once you have pushed it to the browser, you can delete this file with:


unlink($filename);


Launch the page in your browser. You should see the PDF document displayed right inside your browser as shown below:




Troubleshooting

Below are described some of the most common errors encountered by users.

If you get the following error message:


PHP Warning: PHP Startup: pdf: Unable to initialize module

Module compiled with module API=20060613, debug=0, thread-safety=0

PHP compiled with module API=20060613, debug=0, thread-safety=1

These options need to match


It means your PHP is the thread-safe version, but the php_pdf.dll is non thread-safe. Download the thread-safe version of php_pdf.dll from the official PHP site. It should fix the problem.

If you get the following error message:


PHP Fatal error: Call to undefined function pdf_new() in helloworld_pdf.php on line 3


It means your php_pdf.dll has not been loaded. Check your php.ini and see if you have added the following line:

extension=php_pdf.dll


If the above line already exists and you still get the error, most likely it means the php_pdf.dll is not compatible with your version of PHP. There are many versions of php_pdf.dll floating around on the Internet. Try downloading some of those and see if it works.

There are some compiled php_pdf.dll’s (for older versions of PHP) on pecl4win.php.net.


If you get the following error message:

PHP Fatal error: Uncaught exception ‘PDFlibException’ with message ‘Couldn’t open font file ‘c:windowsfontsarial1.ttf’ for reading (file not found)’ in helloworld_pdf.php

It means your have misspelled the name of the font, or the font does not exist in your Windows font folder.

If you get the following error message:


PHP Fatal error: Uncaught exception ‘PDFlibException’ with message ‘Function must not be called in ‘object’ scope’ in helloworld_pdf.php

Check to see if the output pdf file is still open in your Adobe Acrobat Reader. If it is indeed open in the Acrobat Reader, close the file and try again. The error message should go away.

Lastly, suppose the hello world example given above runs fine from the command line. However, you see nothing when you run the code from the browser.

First, try turning on error reporting in your php.ini and see if there is any error message displayed.

Check to see if the web server has write permission to the directory of the temporary pdf file. I have used ‘c:pdf_example3.pdf’ in the example above. So check if your web server has write permission to c:

You may also comment the line: unlink($filename). Reload the page, and verify that the pdf file pdf_example3.pdf has indeed been generated.

{mospagebreak title=Producing a simple bar graph in a PDF document}

Now that you know the basics of generating a PDF document, you can start playing with the whole suite of PDFlib functions as listed in the PHP Manual.

Below is another sample code that outputs a simple bar graph to a PDF document as shown below:




I have sprinkled many comments in the code, so it should be quite self-explanatory.


<?php

# pdf_example4

# a simple bar graph


// create a new pdf document

$pdf = pdf_new();

$filename = ‘c:pdf_example4.pdf';

pdf_open_file($pdf, $filename);


// start a new page (Letter size)

pdf_begin_page($pdf, 612, 792);


// setup font and print hello world

pdf_set_parameter($pdf, ‘FontOutline’,

‘Arial=c:windowsfontsarial.ttf’);

$font = pdf_findfont($pdf, "Arial", "host", 1);

pdf_setfont($pdf, $font, 16);

pdf_show_xy($pdf, "Simple Bar Graph", 50, 720);


// draw the x and y axis

pdf_moveto($pdf, 50, 690);

pdf_lineto($pdf, 50, 520);

pdf_lineto($pdf, 400, 520);

pdf_stroke($pdf);


// draw the bar chart

$x = 80;

$y = 520;

$w = 40;


// the data and color for each column

$data = array(‘120′,’160′,’300′,’240′);

$color = array(‘#4EC3BC’, ‘#DAA876′, ‘#E29CC8′, ‘#FDE0C6′);


// get into some meat now, cheese for vegetarians;

for ($i=0;$i<count($data);$i++){


// calculate the height of the bar

$y_ht = ($data[$i]/max($data))* 100;


// set the color for each bar

list($r, $g, $b) = hex2rgb($color[$i]);

pdf_setcolor($pdf, "fill", "rgb", $r, $g, $b, 0);


// draw the bar

pdf_rect($pdf, $x, $y, $w, $y_ht);

pdf_fill_stroke($pdf);


// write the bar label

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

pdf_setfont($pdf, $font, 10);

pdf_show_xy($pdf, $data[$i], $x+12, $y-16);


// go to the next bar

$x = $x+$w+40;

}


// done

pdf_end_page($pdf);

pdf_close($pdf);

pdf_delete($pdf);


// send it to browser

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

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

readfile($filename);

unlink($filename);


// function to convert a standard rgb from hex to float

function hex2rgb($hex) {

$color = str_replace(‘#’,”,$hex);

$r = hexdec(substr($color,0,2))/255;

$g = hexdec(substr($color,2,2))/255;

$b = hexdec(substr($color,4,2))/255;

return array($r, $g, $b);

}


?>

Final Words

We’ve come to the end of this article. In this tutorial I’ve shown you how to generate PDF documents on the Windows platform. I’ve also given you a number of complete sample codes that should give you a head start in generating your own PDF documents.

Take some time to explore that various PDFlib functions as listed in the PHP Manual. Just bear in mind that of some of the sample codes there might not work because they might have been written for higher versions of PDFlib.

Have lots of fun generating PDF documents with PHP!

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

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort