2009年4月28日 星期二

Generate PDFs with PHP

One of the reasons I like PHP so much is its consistent support for new technologies. The language invites extensibility, making it easy for developers to add new modules to the core engine, and widespread community support has made PHP one of the most full-featured Web programming languages around, with support for a wide variety of modular extensions. Extensions available today allow developers to use PHP to perform IMAP and POP3 operations; dynamically construct images and Shockwave Flash movies; perform credit card validation; encrypt sensitive data; and parse XML-encoded data.

This isn't all, though. One of the more interesting items currently being bundled with PHP is the PDFLib extension, which allows developers to dynamically generate documents in Adobe Portable Document Format (PDF). Over the next few pages, I'm going to take a quick look at this module, providing you with a brief overview of its functions and demonstrating how you can use it in your PHP development. So come on in, and let's get going!

Getting Started

In order to use PHP's PDF manipulation capabilities, you need to have the PDFLib library installed on your system. If you're working on Linux, you can download a copy from http://www.pdflib.com/pdflib/index.html and compile it for your box. If you're running Windows, your job is even simpler - a pre-built PDF library is bundled with your distribution, and all you need to do is activate it by uncommenting the appropriate lines in your PHP configuration file.Additionally, you'll need a copy of the (free!) Adobe Acrobat PDF reader, so that you can view the documents created via the PDFLib library. You can download a copy of this reader from http://www.adobe.com/ Once you've got everything in place, it's time to create a simple PDF file. Here goes:

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

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

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

// get and use a font object
$arial = pdf_findfont($pdf, "Arial", "host", 1); pdf_setfont($pdf, $arial, 10);

// print text
pdf_show_xy($pdf, "There are more things in heaven and earth, Horatio,", 50, 750); pdf_show_xy($pdf, "than are dreamt of in your philosophy", 50, 730);

// end page
pdf_end_page($pdf);

// close and save file
pdf_close($pdf);


Save this file, and then browse to it through your Web browser. PHP will execute the script, and a new PDF file will be created and stored in the location specified at the top of the script. Here's what you'll see when you open the file:

Source :
http://www.sitepoint.com/article/generate-pdfs-php


沒有留言:

張貼留言