`
xiqiao1229
  • 浏览: 12789 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

Generate PDF files from Java applications dynamically

阅读更多

 

Many applications demand dynamic generation of PDF documents. Such applications range from banks generating customer statements for e-mail delivery to readers buying specific book chapters and receiving them in PDF format. The list is endless. In this article, we will use the iText Java library to generate PDF documents. I'll take you through a sample application so you can do it yourself and understand it better.

Get familiar with iText

iText is a freely available Java library from Lowagie.com (see Resources). The iText library is powerful and supports the generation of HTML, RTF, and XML documents, in addition to generating PDFs. You can choose from a variety of fonts to be used in the document. Also, the structure of iText allows you to generate any of the above-mentioned types of documents with the same code.

The iText library contains classes to generate PDF text in various fonts, generate tables in PDF document, add watermarks to pages, and so on. There are many more features available with iText. It would not be possible to demonstrate all of them in a single article. We will cover the basics required for PDF generation.

We will use Eclipse for the development of our sample application. Being an open source IDE, Eclipse is freely available and quite powerful. You can download Eclipse now (see Resources).

The iText API: Closer look

The com.lowagie.text.Document is the main class for PDF document generation. This is the first class to be instantiated. Once the document is created, we would require a writer to write into it. The com.lowagie.text.pdf.PdfWriter is a PDF writer. Some of the other commonly used classes are given below:

  • com.lowagie.text.Paragraph -- This class represents an indented paragraph.
  • com.lowagie.text.Chapter -- This class represents a chapter in the PDF document. It is created using a Paragraph as title and an int as chapter number.
  • com.lowagie.text.Font -- This class contains all specifications of a font, such as family of font, size, style, and color. Various fonts are declared as static constants in this class.
  • com.lowagie.text.List -- This class represents a list, which, in turn, contains a number of ListItems.
  • com.lowagie.text.Table -- This class represents a table that contains cells, ordered in a matrix.

Downloading and configuring iText in Eclipse

Being a pure Java library, iText comes in the form of a JAR file (see Resources). Once you have downloaded the library (let's say, at path C:\temp), the following steps will configure the iText library in an Eclipse environment:

  1. Create a new Java project in Eclipse named iText.
  2. Right-click on the iText project in Package Explorer view and select Properties.
  3. Click Java Build Path. On the Libraries tab, click Add External JARs.
  4. Browse to the C:\temp directory and select the itext-1.3.jar in this directory.
  5. Click OK.

iText is now configured, and Eclipse is ready to create Java applications to generate dynamic PDF documents.

Sample application

What can demonstrate any technology better than a working sample, created by your own hands? Now that you have the requisite tools (Eclipse IDE) and libraries (iText library), we are all set to design and develop a sample running program.

Let's create a simple PDF document that contains some basic elements like plain text, colored text with nondefault font, table, list, chapter, section, etc. The purpose of this application is to familiarize you with the way to use iText library. There are plenty of classes that do lots of work for you related to PDF document generation. It will not be possible to cover all those classes. The javadocs of iText are a good source of information on how to use those classes. Let's start coding.

The first step is to create a document. A document is the container for all the elements of a PDF document.


Listing 1. Instantiation of document object

Document document = new Document(PageSize.A4, 50, 50, 50, 50);

 

The first argument is the page size. The next arguments are left, right, top, and bottom margins, respectively. The type of this document is not yet defined. It depends on the type of writer you create. For our sample, we choose com.lowagie.text.pdf.PdfWriter. Other writers are HtmlWriter, RtfWriter, XmlWriter, and several others. Their names explain their purposes self-sufficiently.


Listing 2. Creation of PdfWriter object

PdfWriter writer = PdfWriter.getInstance(document, \

new FileOutputStream("C:\\ITextTest.pdf"));

document.open();

 

The first argument is the reference to the document object, and the second argument is the absolute name of file in which output will be written. Next, we open the document for writing.

Now, we will add some text on the first page of the document. Any text is added with the help of com.lowagie.text.Paragraph. You can create a default paragraph with your text and default settings of font, color, size, and so on. Otherwise, you can provide your own font. Let's see both options.


Listing 3. Creation of paragraph object

document.add(new Paragraph("First page of the document."));

document.add(new Paragraph("Some more text on the \

first page with different color and font type.", 

FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new Color(255, 150, 200))));

 

Given below is sample output of the above code. Add document.close(); at the end of above code to close the document.


Figure 1. Sample output of above code
Sample output of above code

You just saw how to add plain text into PDF document. Next, we need to add some complex elements into the document. Let's start with creating a new chapter. A chapter is a special section, which starts with a new page and has a number displayed by default.


Listing 4. Creation of chapter object

Paragraph title1 = new Paragraph("Chapter 1", 

           FontFactory.getFont(FontFactory.HELVETICA, \

           18, Font.BOLDITALIC, new Color(0, 0, 255)));

Chapter chapter1 = new Chapter(title1, 1);

chapter1.setNumberDepth(0);

 

In the code above, we created a new chapter object, chapter1, with the title "This is Chapter 1." Setting number depth to 0 will not display the chapter number on page.

A section is a subelement of a chapter. In the following code, we create a section with the title "This is Section 1 in Chapter 1." To add some text under this section, we create another paragraph object, someSectionText, and add it to section object.


Listing 5. Creation of section object

Paragraph title11 = new Paragraph("This is Section 1 in Chapter 1", 

           FontFactory.getFont(FontFactory.HELVETICA, 16, \

           Font.BOLD, new Color(255, 0, 0)));

Section section1 = chapter1.addSection(title11);

Paragraph someSectionText = new Paragraph("This \

text comes as part of section 1 of chapter 1.");

section1.add(someSectionText);

someSectionText = new Paragraph("Following is a 3 X 2 table.");

section1.add(someSectionText);

 

Before we add the table, let's look at what our document looks like. Add following two lines to close the document, then compile and execute the program to generate the PDF document: document.add(chapter1);document.close();.


Figure 2. Sample output of chapter
Sample output of chapter

Next, we create a table object. A table contains a matrix of rows and columns. A cell in a row can span more than one column. Similarly, one cell in a column can span more then one row. Hence, a 3 x 2 table need not have exactly six cells.


Listing 6. Creation of table object

Table t = new Table(3,2);

t.setBorderColor(new Color(220, 255, 100));

t.setPadding(5);

t.setSpacing(5);

t.setBorderWidth(1);

Cell c1 = new Cell("header1");

c1.setHeader(true);

t.addCell(c1);

c1 = new Cell("Header2");

t.addCell(c1);

c1 = new Cell("Header3");

t.addCell(c1);

t.endHeaders();

t.addCell("1.1");

t.addCell("1.2");

t.addCell("1.3");

section1.add(t);

 

In the code above, we create a table object, t, with three columns and two rows. Then we set the border color of the table. Padding is used for spacing between text in the cell and the boundaries of the cell. Spacing is the space between boundaries of neighboring cells. Next, we create three cell objects, with different text. We keep on adding them into the table. They are added in the first row, starting from the first column, moving to the next column in the same row. Once the row is complete, the next cell is added to the first column of the next row. A cell can also be added to the table by just providing the text of the cell, such ast.addCell("1.1");. At the end, the table object is added to the section object.

Finally, let's see how to add a list to the PDF document. A list contains a number of ListItems. A list can be numbered or non-numbered. Passing the first argument as true means you want to create the numbered list.


Listing 7. Creation of list object

List l = new List(true, false, 10);

l.add(new ListItem("First item of list"));

l.add(new ListItem("Second item of list"));

section1.add(l);

 

We had been adding everything to the chapter1 object. Since, there are no more elements to be added to chapter1, it's time to add chapter1 to the main document. We will also close the document object here as we are done with our sample application.


Listing 8. Addition of a chapter to the main document

document.add(chapter1);

document.close();

 

Running the sample application

  1. Download the sample application, j-itextsample.jar (see Download).
  2. Unzip j-itextsample.jar in a directory. If you extract it into C:\temp, for example, this places the source and class files into C:\temp\com\itext\test.
  3. Open a command prompt and change the directory to C:\temp.
  4. Set your system's classpath on this command prompt. Include C:\temp\itext-1.3.jar in system's classpath. On Windows®, execute the command set classpath=C:\temp\itext-1.3.jar;%classpath%.
  5. Run the application with the command java com.itext.test.ITextTest.

The program will generate the ITextTest.pdf document at C:\. A screenshot of the second page of the PDF document is given below.


Figure 3. Screenshot of PDF document
Screenshot of PDF document

Conclusion

You have just seen some basic elements of PDF generation. The beauty of iText is that the same element's syntax can be used in different types of writers. Also, the output of the writer can be redirected to the console (in the case of XML and HTML writers), the output stream of servlets (in the case of a response to Web requests for PDF documents), or any other kind of OutputStream. iText also comes in handy in those situations where the response is the same, but the type of response varies from PDF, RTF, HTML, or XML. iText allows you to create watermarks, encrypt the document, and other output niceties.

 

Download

Description Name Size Download method
Sample code os-javapdf-itextsample.jar 3.2KB HTTP

Information about download methods

 

Resources

Learn

Get products and technologies

  • Order the SEK for Linux, a two-DVD set containing the latest IBM trial software for Linux from DB2®, Lotus®, Rational®, Tivoli®, and WebSphere®. 

  • Innovate your next open source development project with IBM trial software, available for download or on DVD.

Discuss




 

分享到:
评论

相关推荐

    Araxis Merge Professional 2012.4162 (x86/x64).part1

    Directly open and compare the text from Microsoft Office (Word and Excel), OpenDocument, PDF and RTF files. Compare images and binary files. Synchronize folders. Perform code reviews and audits. Work...

    Araxis Merge Professional 2012.4162 (x86/x64).part2

    Directly open and compare the text from Microsoft Office (Word and Excel), OpenDocument, PDF and RTF files. Compare images and binary files. Synchronize folders. Perform code reviews and audits. Work...

    VB.NET Developer's Guide(4574).pdf

    Dynamically Creating Menus 326 Exercise 7.3 Adding a Menu to a Form at Design Time 326 Adding Status Bars to Forms 328 Adding Toolbars to Forms 330 Data Binding 332 Simple Data Binding 332 ...

    FastReport.v4.15 for.Delphi.BCB.Full.Source企业版含ClientServer中文修正版支持D4-XE5

    FastReport® VCL is an add-on component that allows your application to generate reports quickly and efficiently. FastReport® provides all the tools necessary for developing reports, including a ...

    opensc-0.12.0.tar.gz

    (but from other directories), then header files from same directory. Fix path to reference headers, remove src/include/ directory. * Various source code fixes and improvements. * OpenSC now depends ...

    VB编程资源大全(英文源码 数据库)

    <END><br>54,udl2.zip This application reads universal data link files from disk, creates them, and saves modifications to them to a file. UDL files contain ADO connection information to data ...

    Visual C++ 编程资源大全(英文源码 其它)

    40.zip Getting rid of Window List from MDI applications 在MDI应用中去掉窗口列表(5KB)<END><br>41,41.zip Save and Restore 存储和恢复(7KB)<END><br>42,42.zip A Quick Start 使用微软本地化...

    Visual C++ 编程资源大全(英文源码 数据库)

    excel_odbc_demo.zip A discussion and demonstration of reading Excel files using ODBC (20KB)<END><br>30,SPCW.zip A tool to generate class files to implement stored procedures(354KB)<END><br>31,...

    微软内部资料-SQL性能优化5

    An index consists of a tree with a root from which the navigation begins, possible intermediate index levels, and bottom-level leaf pages. You use the index to find the correct leaf page. The number ...

    微软内部资料-SQL性能优化2

     Generate a hypothesis based on performance counters captured by System Monitor.  For each hypothesis generated, identify at least two other non-System Monitor pieces of information that would ...

Global site tag (gtag.js) - Google Analytics