Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

developerWorks Community:

  • Close [x]

Understanding the Zend Framework, Part 5: Creating PDF files

Building the perfect reader

Nicholas Chase (nicholas@nicholaschase.com), Developer/Writer, Studio B
Nicholas Chase, a Studio B author, has been involved in Web site development for companies such as Lucent Technologies, Sun Microsystems, Oracle, and the Tampa Bay Buccaneers. Nick has been a high school physics teacher, a low-level radioactive waste facility manager, an online science fiction magazine editor, a multimedia engineer, and an Oracle instructor. More recently, he was the Chief Technology Officer of an interactive communications firm in Clearwater, Florida, USA, and is the author of several books on Web development, including XML Primer Plus (Sams). He's currently trying to buy a farm so he and his wife can raise alpacas and chickens. He loves to hear from readers and can be reached at: nicholas@nicholaschase.com.

Summary:  In previous parts of this "Understanding the Zend Framework" series, you created the basic application, the Chomp online feed reader, using the open source PHP Zend Framework. In this tutorial, you use the Zend Framework's PDF capabilities to generate a PDF document based on entries the user has saved.

View more content in this series

Date:  18 Jan 2011 (Published 01 Aug 2006)
Level:  Intermediate PDF:  A4 and Letter (999 KB | 35 pages)Get Adobe® Reader®

Comments:  

Choosing items and reusing documents

The basic system is in place. You just need to add a couple of refinements. In this section, you'll enable users to choose which saved entries should be included in the document, and you'll enable them to add onto a previous file, rather than creating a new one.

Better item management: Adding an ID

Before you can deal with your entries in any reasonable way, you need a better way to reference them. In the first pass, you created a structure in which items were referenced by feed name, or sometimes by URL, but as you get more serious about data management, each item really needs a primary key you can reference.

To that end, log into MySQL and execute the command shown in Listing 21.


Listing 21. Adding a new column to the table
ALTER TABLE `savedentries` ADD `id` INT NOT NULL 
AUTO_INCREMENT PRIMARY KEY;

This command adds a new primary key called id and specifies that when a new road gets added to the table, this field should provide a new, unique incremented value.


Enabling the user to choose items

The next step is to enable users to decide which items should be part of the PDF. To do that, you will add a second form to the saved entries page. Open the viewSaveEntries.php file and make the changes shown in Listing 22.


Listing 22. Adding PDF generation options to viewSavedEntries.php
...
         echo "<input type='hidden' name='type' value='$type'/>";
         echo "<td><a href='$link'>$title</a></td>";
         echo "<td><input type='submit'
 value='delete'/></td>";
         echo "<td><a href=
'/feed/fullText?feedTitle=$feedTitleamp;channelTitle=$channelTitle'
>$entrysaved</a></td></form></tr>\n";
     }
    ?>
  </table><br>
  <h3>Generate a PDF:</h3>
  <form method='POST' action='/feed/createPdf'>
  <table>
    <tr>
      <td>Feed > Title (Click to View)
        amp;nbsp;amp;nbsp;amp;nbsp;amp;nbsp;amp;nbsp;amp;nbsp;</td>
      <td>Add to PDF</td>
    </tr>
<?php
     foreach ($this->entries as $row) {
         $link = $row['link'];
         $channelTitle = $row['channelname'];
         $feedTitle = $row['feedname'];
         $title = "$feedTitle";
         $entrysaved = '';
         if($row['entrysaved'] == 'true')
         {
             $entrysaved = 'Full Text';
         }
         if ($row['channelname'] != '')
         {
             $title = "$title > $channelTitle";
             $type = 'rssFeed';
         } else {
             $type = 'webPage';
         }
         $id = $row['id'];
         echo "<tr><td><a href='$link'>$title</a></td>";
         echo "<td><input type='checkbox' name='$id' " . 
              "checked='checked'></td></tr>\n";
     }
?>
  </table>
  <input type='Submit' value='Create PDF'>
  </form>
</body>
</html>

This is a generic HTML form, with checkboxes for each id value (see Figure 10).


Figure 10. Enabling the user to choose items
Enabling the user to choose items

Filtering the PDF based on user choices

Now to make this work, you have to look for the checkboxes in the createPdfAction() function (see Listing 23).


Listing 23. Filtering the PDF
...
    public function createPdfAction()
    {
...
        $sql = $select->__toString();
        $entries = $db->fetchAll($sql);

        $startPos = $topPos - 120;

        $filterPost = Zend_Registry::get('fPost');


        foreach($entries as $row){

            if($filterPost->getRaw($row['id']) == "on"){

                $title = $row['feedname'];
                $entrydata = $row['entrydata'];
...
                    $page->drawText($line, 48, $startPos);
                    $startPos = $startPos - 16;

                }
                $startPos = $startPos - 16;
            }
        }

        array_push($pdf->pages, $page);

        header('Content-type: application/pdf');
        echo $pdf->render();

    }
...

Here again, the process is straightforward. You first retrieve the filter you've used in previous parts of this series from the registry, then use it to retrieve the value for the checkbox that corresponds to the ID value of the current entry a being evaluated.

If the box was checked when the form was submitted, the value will be on, and the routine includes the entry in the PDF. If not, it skips the entry. The result is a PDF that includes only the entries that have been specifically requested (see Figure 11).


Figure 11. Filtering the PDF based on the user
Filtering the PDF based on the user

Editing an existing PDF: Adding the option

Finally, you want to give the user the option to use an existing PDF, rather than creating a new one. This can be handy as a way of enabling users to create a backup of saved entries. For example, if a user collects several dozen, or even several hundred, saved entries, he can add them to a PDF file and delete them from the system. When he has more entries to add, he can simply opt to use the previous PDF file. The function adds new items at the end of the document.

First, provide the option to use the existing PDF by adding a checkbox to the viewSaveEntries.php file (see Listing 24).


Listing 24. Choosing to use an existing PDF
...
         if($row['channelname'] != ''){
             $title = "$title > $channelTitle";
             $type = 'rssFeed';
         } else {
             $type = 'webPage';
         }
         $id = $row['id'];
         echo "<tr><td><a href='$link'>$title</a></td>";
         echo "<td><input type='checkbox' name='$id'\
         checked='checked'></td></tr>\n";
     }
?>
  </table>
  Start with existing PDF: <input type='checkbox' 

 name='startExisting' /><br /><br />
  <input type='Submit' value='Create PDF'>
  </form>
</body>
</html>

This adds the checkbox to the end of the form (see Figure 12).


Figure 12. Editing an existing PDF
Editing an existing PDF

Editing an existing PDF: Adding pages

To use an existing PDF, you will need to make changes to the createPdfAction() function (see Listing 25).


Listing 25. Adding pages to an existing PDF document
...
    public function createPdfAction()
    {

        require_once 'Zend/Pdf.php';

       
        $input = new Zend_Filter_Input(
            array('username'=>'StringTrim'),
            array('username'=>'Alpha'),
            $_SESSION);
        $username = $input->getUnescaped('username');

        $input = new Zend_Filter_Input(
            array('*'=>'StringTrim'),
            null,
            $_GET);
        $startExisting = $input->getUnescaped('startExisting');

        $pdf = '';
        if ($startExisting == 'on')
        {
            if (file_exists($username.'.pdf'))
            {
                $pdf = Zend_Pdf::load($username.'.pdf');
            }
            else
            {
                $pdf = new Zend_Pdf();
            }
        }
        else
        {
            $pdf = new Zend_Pdf();
        }

        $page = $this->newPdfPage();
        $chompImage = Zend_Pdf_Image::imageWithPath(
                        'E:\sw\public_html\chomp.jpg');

...
                }
                $startPos = $startPos - 16;
            }
        }

        array_push($pdf->pages, $page);

        $pdf->save($username . '.pdf');

        header('Content-type: application/pdf');
        echo $pdf->render();

    }
...

First, note that the username check has been moved to the top of the function because if there is an existing PDF file, it will be named username.pdf. Next, if the user did choose to use an existing PDF, you check to see whether one already exists. If so, you use the load() function to load the document as the basis for the $pdf object. If not, or if the user did not choose to use existing document, you simply create a new one.

From here, processing proceeds exactly as before, except that before you render the PDF to the browser, you save it to the server for next time.

5 of 9 | Previous | Next

Comments



static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Open source
ArticleID=148418
TutorialTitle=Understanding the Zend Framework, Part 5: Creating PDF files
publish-date=01182011
author1-email=nicholas@nicholaschase.com
author1-email-cc=dwxed@us.ibm.com