Приглашаем посетить
Литература 20 век (20v-euro-lit.niv.ru)

The PDF Library

Table of Contents
Previous Next

The PDF Library

The free PDFlib is quite a useful extension in that it allows the creation and modification of PDF documents (PDF documents are Adobe's attempt to provide a standardized high-quality document format). Additionally, since this method of creating PDF files is free, it is a great way to create them.

Installation

Installing PDFlib on Windows systems is quite easy: copy the dynamic extension (php_pdf.dll) to your "extensions" directory (if it is not already there), and uncomment extension=php_pdf.dll in php.ini.

Installing on UNIX and UNIX flavored systems, however, can be quite a different story. There are two different methods of adding PDFlib support to these systems: using loadable modules, as with Windows, or by building PDFlib into PHP. The latter method is quite a difficult task, as you must rebuild PHP to incorporate the support. Before installing PDFlib, however, you will need to install LibTIFF and LibJPEG, which can be found at http://www.libtiff.org/ and ftp://ftp.uu.net/graphics/jpeg/, respectively.

Important 

The binary distribution of PDFlib is for commercial licensing only. If you would like to use the PDF Import Library (also referred to as PDI), you must use the binary version of PDFlib, as PDI is not available in the source form.

To install PDFlib as a loadable module, which is the recommended way of installing PDFlib on your system, you must first make sure the following conditions are met:

  • PDFlib support must not have already been compiled into PHP. You can check this by using the phpinfo() function. If you see a line in the configure script that says --with - pdflib=yes or --with-pdflib=<dir>, you will need to recompile PHP with the --with - pdflib=no configuration option.

  • The module must be placed in the directory set as the extensions directory in php.ini.

  • php.ini must include both safe_mode=Off and enable_dl=On.

  • Properties of your PHP version must match the loadable module build – your build must not be a debug version and it must be thread safe. If you get an error, you may want to check the <pdflib-directory>/bind/php/ directory, which may contain a module that will work with your specific build of PHP.

If you have already compiled PDFlib into PHP and are wondering why you would want to use the pre- built binary module, it contains PDI support, which is, as previously mentioned, not found in the sources. Currently, dynamic modules for PHP 4.0.4pl1, PHP 4.0.5, and PHP 4.0.6 (for UNIX and Windows) are available in the distributed tarball.

Once the extension has been copied to the directory specified in php.ini, you should load it using the extension=php_pdf.dll or extension=libpdf_php.so. If you don't wish to add this line to your php.ini file, you can include PDFlib support in individual files using the dl("<pdflib_module>") function. Using the dl() function can be quite beneficial when PHP is running as a CGI process (as opposed to running as a module) and allows the extension to be loaded as needed, as opposed to every time a new process of PHP is started.

To build PDFlib support into PHP, you will need to follow these steps:

  • Unpack the PDFlib distribution (binary or source) to <pdflib_directory> and run "make" and "make install".

  • Copy the PDFlib files for PHP into your PHP source tree with "cp <pdflib_directory>/bind/php/ext/pdf/* <php_directory>/ext/pdf".

  • When rebuilding PHP with PDFlib from source, configure PHP with "--with - pdflib[=<pdflib_installation_directory>]" where the installation directory will be your operating system distribution's equivalent of /usr/lib/. Otherwise, configure PHP with "--with-pdflib=<pdflib_directory>/bind/c".

  • Rebuild PHP as you normally would ("make; make install").

Using PDFlib

The PDFlib functions are self-explanatory and most are generally easy to use. The only hard thing about PDFlib is the fact that scripting a document takes longer than actually writing one, thus the actual creation of a PDF document can get a tad confusing.

Assuming we have built PDFlib into PHP (or included it in our php.ini file), we can make a simple PDF file with PHP, containing very simple information. This may look like quite a bit of code just to create a PDF file that says "Sample Text in Arial Font!". Fortunately, most of the following commands are parts of a template for any other PDF document you wish to create.

This text will come at the top of any PHP-generated PDF document you write:

    <?php
    //pdfdemo.php

    $pdfFile = pdf_new();
    PDF_open_file($pdfFile, "");

Here, we set standard PDF document information about who created this document, and what it is for:

    pdf_set_info($pdfFile, "Author", "Devon O'Dell");
    pdf_set_info($pdfFile, "Creator", "Devon O'Dell");
    pdf_set_info($pdfFile, "Title", "PDFlib Demonstration");
    pdf_set_info($pdfFile, "Subject", "Demonstrating the PDFlib");

This line begins a new page. You will probably want to use 595 and 842 for the width and height of your document every time you make a new one, as these values are the standard size of a page:

    pdf_begin_page($pdfFile, 595, 842);

This function adds a bookmark for the following page. This is quite useful if we have multiple sections in our document and need to jump around with a table of contents (TOC). When using this function, the PDF reader will automatically make a TOC at the right hand side of the screen which allows users to jump around to different pages in the document quickly, based upon the topic:


    pdf_add_bookmark($pdfFile, "Page 1");

We now select a font to use. We'll use Arial, with encoding type "winansi" and set the 1 flag at the end to indicate that we wish this font to be embedded into the PDF document. If we cannot find the font on the system, we simply output a friendly error message, clean up, and quit (we don't want to give a blank PDF document to the user):

    if ($font = pdf_findfont($pdfFile, "Arial", "winansi", 1)) {
        PDF_setfont($pdfFile, $font, 12);
    } else {
        echo("Font Not Found.");
        pdf_end_page($pdfFile);
        pdf_close($pdfFile);
        pdf_delete($pdfFile);
        exit;
    }

The actual meat of the page is defined here. We want to start writing at point 50, 780 in this page to allow some margin between the left and top of the PDF document:

    pdf_show_xy($pdfFile, "Sample Text in Arial Font", 50, 780);

Here we indicate that we are ending our page, and free our document-related resources to get some memory back. All PDF resources are freed when the script finishes execution:

    pdf_end_page($pdfFile);
    pdf_close($pdfFile);

Now we store the PDF contents into a variable called $pdf, and we also store its length to $pdfLen. It is necessary to store the length of the file because we need to alert the browser to the size of the inline document we are sending to it:

    $pdf = pdf_get_buffer($pdfFile);
    $pdfLen = strlen($pdf);

We need to tell the browser to expect a PDF document, so we need to send the following headers to the browser. The filename field in Content-Disposition is inconsequential because it is being sent inline with the rest of the information contained in the "page":

    header("Content-type: application/pdf");
    header("Content-Length: $pdfLen");
    header("Content-Disposition: inline; filename=phpMade.pdf");

We can now easily print the PDF buffer directly to the browser, since it knows that a PDF file is coming its way:

    print($pdf);

Now, we delete the PDF object, and free all the system-related resources:

    pdf_delete($pdfFile);
    ?>

When creating PDF documents, remember that the PDF coordinate system revolves around Quadrant 1. This means that the origin (0, 0) is located at the bottom left corner of the page. This is most likely the exact opposite of what you are used to when working with images, or programs that use the Quadrant 4 coordinate system.

How does all this fit into anything oriented towards real-world applications? It's quite useful if, for example, we are making a dynamic manual system, which we will explore next. We will use PHP to retrieve information from a MySQL database, and load it into a manual.

First, we will need to make a database for storing our manual entries:

    CREATE DATABASE manual;

    USE manual;

    CREATE TABLE manual.entries (
        id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
        topic VARCHAR(100) NOT NULL UNIQUE,
        content BLOB NOT NULL
    );

Now let's create a simple administration script from which we can add entries into the database:

    <?php
    //admin.php

    if (!$submit) {
    ?>

      <html>
        <head><title>Admin.php</title></head>
        <body>
          <form action="<?php echo($PHP_SELF); ?>" method="POST">
            Topic: <input type=text maxlength=100 name=topic><br>
            Content:<br>
            <textarea rows=80 cols=25 name=content></textarea><br>
            <input type=submit name=submit>
          </form>
        </body>
      </html>

    <?php
    } else {
        if (@mysql("manual", "INSERT INTO entries (id, topic, content)
                              VALUES (NULL, '$topic', '$content')")) {
            echo("Successfully added information into database");
    } else {
            echo("Error: " . mysql_error());
        }
    }
    ?>

Now we can create our "manual" with the following code. We start with the usual PDF functions:

    <?php
    //manual.php

    //Create a new PDF object and "open" it as inline
    $pdfFile = pdf_new();
    pdf_open_file($pdfFile, "");

    //Set miscellaneous information
    pdf_set_info($pdfFile, "Author", "Devon O'Dell");
    pdf_set_info($pdfFile, "Creator", "Devon O'Dell");
    pdf_set_info($pdfFile, "Title", "PDFlib Demonstration");
    pdf_set_info($pdfFile, "Subject", "Demonstrating the PDFlib");

First we get the entries from the database:

    $entries = mysql("manual", "SELECT * FROM entries");

Then we set up a for loop to grab information for each entry:

    for ($index = 0; $index < mysql_num_rows($entries); $index++) {

        //Grab information for the current row
        $entry = mysql_fetch_array($entries);

        //Start a new page
        pdf_begin_page($pdfFile, 595, 842);

        //Add a bookmark with the name of the entry topic
        pdf_add_bookmark($pdfFile, $entry['topic']);

        //Set the font to 9 point Arial or give an error message
        if ($font = pdf_findfont($pdfFile, "Arial", "winansi", 1)) {
            PDF_setfont($pdfFile, $font, 9);
        } else {
            echo("Font Not Found.");

            pdf_end_page($pdfFile);
            pdf_close($pdfFile);
            pdf_delete($pdfFile);

            exit;
        }

Here's where we print the content from the database at the specified point:

        pdf_show_xy($pdfFile, $entry['content'], 50, 780);

We'll end the page inside the loop so that we can begin a new one when we enter the loop again:

        pdf_end_page($pdfFile);
    }

The final part of the file is made up of more standard PDF functions:

    //Close the $pdfFile
    pdf_close($pdfFile);

    //Get ready to output
    $pdf = pdf_get_buffer($pdfFile);
    $pdfLen = strlen($pdf);

    //Send relevant headers
    header("Content-type: application/pdf");
    header("Content-Length: $pdfLen");
    header("Content-Disposition: inline; filename=phpMade.pdf");

    //Send the info to the browser
    print($pdf);

    //Get rid of the object.
    pdf_delete($pdfFile);
    ?>

Table of Contents
Previous Next