Home / Articles / Tools of the Trade, Part 1: Creating PDF documents with iText

Tools of the Trade, Part 1: Creating PDF documents with iText

  • Date: Nov 4, 2005.

Article Description

Have you ever wanted to create your own PDF documents without having to first shell out money for PDF-creation software? Good news: You can create those documents with nothing more than Java and iText. This freely available Java library provides the classes for easily constructing PDF documents and adding various kinds of content (such as paragraphs, lists, tables, and images) to those documents. This article by Jeff Friesen, the first in a three-part series that explores useful open-source tools, introduces you to iText and shows you how to create many interesting PDF documents without having to first spend money on PDF-creation software.

Planetary PDF

This article has covered lots of material. Your head is probably spinning from exploring many of the capabilities offered by iText. Perhaps you are asking yourself how to combine these capabilities to create useful PDF documents. If so, I have an answer: a more extensive PDF project that brings together many of the capabilities that were presented earlier.

The project I have in mind is to write an application that creates a PDF document called planets.pdf, which tours the planets in our solar system. It contains a title page, an introduction, one chapter per planet, and an appendix that compares each planet's orbit, diameter, and mass. Figure 17 shows what I have in mind.

Figure 17

Figure 17 The planetary PDF document.

Don't worry. You do not have to create the application that generates Figure 17's PDF document. I have done all of that work for you. You can download the code here, and the application's source code appears in Listing 15. As you examine that source code, you will discover that there is nothing you have not seen before.

Listing 15 Planets.java

// Planets.java

import java.awt.Color;
import java.io.*;

import com.lowagie.text.*;
import com.lowagie.text.pdf.*;

class Planets
{
  public static void main (String [] args) throws Exception
  {
   Document doc = new Document ();

   PdfWriter writer;
   writer = PdfWriter.getInstance (doc,
                   new FileOutputStream ("planets.pdf"));
   writer.setViewerPreferences (PdfWriter.PageModeUseOutlines);

   doc.open ();

   // Establish a footer that shows the page number between a pair dashes.

   HeaderFooter footer = new HeaderFooter (new Phrase ("- "),
                       new Phrase (" -"));
   footer.setAlignment (Element.ALIGN_CENTER);

   doc.setFooter (footer);

   // Create the title page.

   PdfContentByte cb = writer.getDirectContent ();

   cb.rectangle (doc.left (), doc.bottom (), doc.right () - doc.left (),
          doc.top ()-doc.bottom ());

   cb.stroke ();

   cb.beginText ();

   BaseFont bf = BaseFont.createFont (BaseFont.HELVETICA,
                     BaseFont.CP1252,
                     BaseFont.NOT_EMBEDDED);
   cb.setFontAndSize (bf, 36);

   cb.showTextAligned (PdfContentByte.ALIGN_CENTER, "The Planets",
             (doc.right ()-doc.left ()) / 2 + doc.leftMargin (),
             (doc.top ()-doc.bottom ()) / 2 + doc.topMargin (),
             0);

   cb.endText ();

   // Establish a title font for all chapter titles.

   Font titleFont = new Font (Font.HELVETICA, 18, Font.BOLD, 
                 new Color (0, 0, 128));

   // Create the Introduction chapter.

   Paragraph title = new Paragraph ("Introduction", titleFont);
   title.setAlignment (Element.ALIGN_CENTER);
   title.setSpacingAfter (18.0f);

   Chapter chapter = new Chapter (title, 0);
   chapter.setNumberDepth (0);

   Paragraph p = new Paragraph ("The solar system is an amazing place. " +
                  "We are learning so much about the " +
                  "planets and their moons, thanks to the " +
                  "efforts of spacecraft and their human " +
                  "controllers. This document provides a " +
                  "brief introduction to our solar " +
                  "system's nine planets.");
   p.setAlignment (Element.ALIGN_JUSTIFIED);
   chapter.add (p);

   doc.add (chapter);

   // Create the Mercury chapter.

   title = new Paragraph ("Mercury", titleFont);

   title.setAlignment (Element.ALIGN_CENTER);
   title.setSpacingAfter (18.0f);

   chapter = new Chapter (title, 1);
   chapter.setNumberDepth (0);
   chapter.setBookmarkOpen (false);
   chapter.setBookmarkTitle ("Chapter 1: Mercury");

   p = new Paragraph ("Mercury, the closest planet to the sun and the " +
             "eighth largest planet, is named after the Roman " +
             "god of commerce, travel, and thievery.");
   p.setAlignment (Element.ALIGN_JUSTIFIED);
   chapter.add (p);

   Image image = Image.getInstance ("mercury.gif");
   image.setAlignment (Image.ALIGN_MIDDLE);
   chapter.add (image);

   chapter.add (new Paragraph ("Vital statistics:"));

   List list = new List (false, 30);
   list.add (new ListItem ("Orbit: 57,910,000 kilometers"));
   list.add (new ListItem ("Diameter: 4,880 kilometers"));
   list.add (new ListItem ("Mass: 3.3e23 kilograms"));
   chapter.add (list);

   doc.add (chapter);

   // Create the Venus chapter.

   title = new Paragraph ("Venus", titleFont);
   title.setAlignment (Element.ALIGN_CENTER);
   title.setSpacingAfter (18.0f);

   chapter = new Chapter (title, 2);
   chapter.setNumberDepth (0);
   chapter.setBookmarkTitle ("Chapter 2: Venus");

   p = new Paragraph ("Venus, the second planet from the sun and the " +
             "sixth largest planet, is named after the Roman " +
             "goddess of love and beauty.");
   p.setAlignment (Element.ALIGN_JUSTIFIED);
   chapter.add (p);

   image = Image.getInstance ("venus.gif");
   image.setAlignment (Image.ALIGN_MIDDLE);
   chapter.add (image);

   chapter.add (new Paragraph ("Vital statistics:"));

   list = new List (false, 30);
   list.add (new ListItem ("Orbit: 108,200,000 kilometers"));
   list.add (new ListItem ("Diameter: 12,103.6 kilometers"));
   list.add (new ListItem ("Mass: 4.869e24 kilograms"));
   chapter.add (list);

   doc.add (chapter);

   // Create the Earth chapter.

   title = new Paragraph ("Earth", titleFont);
   title.setAlignment (Element.ALIGN_CENTER);
   title.setSpacingAfter (18.0f);

   chapter = new Chapter (title, 3);
   chapter.setNumberDepth (0);
   chapter.setBookmarkTitle ("Chapter 3: Earth");

   p = new Paragraph ("Earth, the third planet from the sun and the " +
             "third largest planet, has a name not derived " +
             "from mythology.");
   p.setAlignment (Element.ALIGN_JUSTIFIED);
   chapter.add (p);

   image = Image.getInstance ("earth.gif");
   image.setAlignment (Image.ALIGN_MIDDLE);
   chapter.add (image);

   chapter.add (new Paragraph ("Vital statistics:"));

   list = new List (false, 30);
   list.add (new ListItem ("Orbit: 149,600,000 kilometers"));
   list.add (new ListItem ("Diameter: 12,756.3 kilometers"));
   list.add (new ListItem ("Mass: 5.972e24 kilograms"));
   chapter.add (list);

   doc.add (chapter);

   // Create the Mars chapter.

   title = new Paragraph ("Mars", titleFont);
   title.setAlignment (Element.ALIGN_CENTER);
   title.setSpacingAfter (18.0f);

   chapter = new Chapter (title, 4);
   chapter.setNumberDepth (0);
   chapter.setBookmarkTitle ("Chapter 4: Mars");

   p = new Paragraph ("Mars, the fourth planet from the sun and the " +
             "seventh largest planet, is named after the Roman " +
             "god of war.");
   p.setAlignment (Element.ALIGN_JUSTIFIED);
   chapter.add (p);

   image = Image.getInstance ("mars.gif");
   image.setAlignment (Image.ALIGN_MIDDLE);
   chapter.add (image);

   chapter.add (new Paragraph ("Vital statistics:"));

   list = new List (false, 30);
   list.add (new ListItem ("Orbit: 227,940,000 kilometers"));
   list.add (new ListItem ("Diameter: 6,794 kilometers"));
   list.add (new ListItem ("Mass: 6.4219e23 kilograms"));
   chapter.add (list);

   doc.add (chapter);

   // Create the Jupiter chapter.

   title = new Paragraph ("Jupiter", titleFont);
   title.setAlignment (Element.ALIGN_CENTER);
   title.setSpacingAfter (18.0f);

   chapter = new Chapter (title, 5);
   chapter.setNumberDepth (0);
   chapter.setBookmarkTitle ("Chapter 5: Jupiter");

   p = new Paragraph ("Jupiter, the fifth planet from the sun and the " +
             "largest planet, is named after the Roman king of " +
             "the gods.");
   p.setAlignment (Element.ALIGN_JUSTIFIED);
   chapter.add (p);

   image = Image.getInstance ("jupiter.gif");
   image.setAlignment (Image.ALIGN_MIDDLE);
   chapter.add (image);

   chapter.add (new Paragraph ("Vital statistics:"));

   list = new List (false, 30);
   list.add (new ListItem ("Orbit: 778,330,000 kilometers"));
   list.add (new ListItem ("Diameter: 142,984 kilometers (equatorial)"));
   list.add (new ListItem ("Mass: 1.9e27 kilograms"));
   chapter.add (list);

   doc.add (chapter);

   // Create the Saturn chapter.

   title = new Paragraph ("Saturn", titleFont);
   title.setAlignment (Element.ALIGN_CENTER);
   title.setSpacingAfter (18.0f);

   chapter = new Chapter (title, 6);
   chapter.setNumberDepth (0);
   chapter.setBookmarkTitle ("Chapter 6: Saturn");

   p = new Paragraph ("Saturn, the sixth planet from the sun and the " +
             "second-largest planet, is named after the Roman " +
             "god of agriculture.");
   p.setAlignment (Element.ALIGN_JUSTIFIED);
   chapter.add (p);

   image = Image.getInstance ("saturn.gif");
   image.setAlignment (Image.ALIGN_MIDDLE);
   chapter.add (image);

   chapter.add (new Paragraph ("Vital statistics:"));

   list = new List (false, 30);
   list.add (new ListItem ("Orbit: 1,429,400,000 kilometers"));
   list.add (new ListItem ("Diameter: 120,536 kilometers (equatorial)"));
   list.add (new ListItem ("Mass: 5.68e26 kilograms"));
   chapter.add (list);

   doc.add (chapter);

   // Create the Uranus chapter.

   title = new Paragraph ("Uranus", titleFont);
   title.setAlignment (Element.ALIGN_CENTER);
   title.setSpacingAfter (18.0f);

   chapter = new Chapter (title, 7);
   chapter.setNumberDepth (0);
   chapter.setBookmarkTitle ("Chapter 7: Uranus");

   p = new Paragraph ("Uranus, the seventh planet from the sun and the " +
             "third largest planet (by diameter), is named " +
             "after the Greek deity of the Heavens.");
   p.setAlignment (Element.ALIGN_JUSTIFIED);
   chapter.add (p);

   image = Image.getInstance ("uranus.gif");
   image.setAlignment (Image.ALIGN_MIDDLE);
   chapter.add (image);

   chapter.add (new Paragraph ("Vital statistics:"));

   list = new List (false, 30);
   list.add (new ListItem ("Orbit: 2,870,990,000 kilometers"));
   list.add (new ListItem ("Diameter: 51,118 kilometers (equatorial)"));
   list.add (new ListItem ("Mass: 8.683e25 kilograms"));
   chapter.add (list);

   doc.add (chapter);

   // Create the Neptune chapter.

   title = new Paragraph ("Neptune", titleFont);
   title.setAlignment (Element.ALIGN_CENTER);
   title.setSpacingAfter (18.0f);

   chapter = new Chapter (title, 8);
   chapter.setNumberDepth (0);
   chapter.setBookmarkTitle ("Chapter 8: Neptune");

   p = new Paragraph ("Neptune, the eighth planet from the sun and the " +
             "fourth largest planet, is named after the Roman " +
             "god of the sea.");
   p.setAlignment (Element.ALIGN_JUSTIFIED);
   chapter.add (p);

   image = Image.getInstance ("neptune.gif");
   image.setAlignment (Image.ALIGN_MIDDLE);
   chapter.add (image);

   chapter.add (new Paragraph ("Vital statistics:"));

   list = new List (false, 30);
   list.add (new ListItem ("Orbit: 4,504,000,000 kilometers"));
   list.add (new ListItem ("Diameter: 49,532 kilometers (equatorial)"));
   list.add (new ListItem ("Mass: 1.0247e26 kilograms"));
   chapter.add (list);

   doc.add (chapter);

   // Create the Pluto chapter.

   title = new Paragraph ("Pluto", titleFont);
   title.setAlignment (Element.ALIGN_CENTER);
   title.setSpacingAfter (18.0f);

   chapter = new Chapter (title, 9);
   chapter.setNumberDepth (0);
   chapter.setBookmarkTitle ("Chapter 9: Pluto");

   p = new Paragraph ("Pluto, usually the farthest planet from the sun " +
             "and the smallest planet, is named after the " +
             "Roman god of the underworld.");
   p.setAlignment (Element.ALIGN_JUSTIFIED);
   chapter.add (p);

   image = Image.getInstance ("pluto.gif");
   image.setAlignment (Image.ALIGN_MIDDLE);
   chapter.add (image);

   chapter.add (new Paragraph ("Vital statistics:"));

   list = new List (false, 30);
   list.add (new ListItem ("Orbit: 5,913,520,000 kilometers (average)"));
   list.add (new ListItem ("Diameter: 2274 kilometers"));
   list.add (new ListItem ("Mass: 1.27e22 kilograms"));
   chapter.add (list);

   doc.add (chapter);

   // Create the Appendix chapter.

   title = new Paragraph ("Planetary Comparison", titleFont);
   title.setAlignment (Element.ALIGN_CENTER);
   title.setSpacingAfter (18.0f);

   chapter = new Chapter (title, 0);
   chapter.setNumberDepth (0);
   chapter.setBookmarkTitle ("Appendix A: Planetary Comparison");

   p = new Paragraph ("The following table compares the nine solar " +
             "system planets in terms of orbit, diameter, and " +
             "mass. It only shows two planet entries because " +
             "I want you to add the remaining planet entries " +
             "to this table (as an exercise). Also, feel free " +
             "to expand this table with additional columns " +
             "that present other statistics, if desired.");
   p.setAlignment (Element.ALIGN_JUSTIFIED);
   p.setSpacingAfter (24.0f);
   chapter.add (p);

   PdfPTable table = new PdfPTable (4);

   table.addCell ("Planet");
   table.addCell ("Orbit (km)");
   table.addCell ("Diameter (km)");
   table.addCell ("Mass (kg)");

   table.addCell ("Mercury");
   table.addCell ("57,910,000");
   table.addCell ("4,880");
   table.addCell ("3.3e23");

   table.addCell ("Venus");
   table.addCell ("108,200,000");
   table.addCell ("12,103.6");
   table.addCell ("4.869e24");

   chapter.add (table);

   doc.add (chapter);

   doc.close ();
  }
}

After reviewing the source code, you might be wondering why chapter.setBookmarkOpen (false);—part of the code that creates the first chapter—is present. This method call exists to suppress the display of a chapter's sections on the Bookmarks pane. But Listing 15 adds no sections to any chapter. What gives?

The method call is a hint that the source code is unfinished. I believe the best way for you to understand this iText tool is to continue developing Listing 15. For example, after adding the remaining seven rows to the table in the final chapter (the appendix), add some color to that table. Also, add a section to each of the planet chapters that presents information on (and images of) the various moons that orbit the planet. You might even want to discuss the various spacecraft that have visited the planet. Only your imagination limits what you can do to this document with iText.

5. Conclusion | Next Section Previous Section

Adobe Press Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Adobe Press and its family of brands. I can unsubscribe at any time.

Overview

Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Adobe Press products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security

Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children

This site is not directed to children under the age of 13.

Marketing

Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out

Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.adobepress.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links

This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020