Dynamically generate PDF files from Java applications

Source: Internet
Author: User
Dynamically generate a PDF file from a Java application-general Linux technology-Linux programming and kernel information. The following is a detailed description. If the application needs to dynamically generate a PDF file, the iText library is required. The Open Source iText library enables the creation of PDF documents to be completed instantly. This article introduces iText and provides? Quick Start Guide for generating PDF documents using technical applications. We have created a sample application to better understand iText.


Many applications require dynamic generation of PDF documents. Such applications include generating client reports for Email Delivery by banks, Purchasing specific book chapters for readers, and receiving these documents in PDF format. There are many examples listed below. In this article, we will use the iText Java library to generate a PDF document and guide you through a sample application, so that you can better understand and use iText.

   Familiar with iText

IText is a free Java library provided by the Lowagie.com site (see references. The iText library is powerful and supports generating HTML, RTF, and XML documents. In addition, it can generate PDF documents. You can select the font used in the document from multiple fonts. At the same time, the iText structure allows the same code to generate any of the above types of documents.

The classes in the iText library are used to generate PDF text in various fonts, generate tables in PDF documents, and add watermarks to pages. IText also provides many features. It is not possible to demonstrate it one by one in an article. This document describes the basic requirements for generating PDF documents.

We will use Eclipse for sample application development. As an open-source IDE, you can get Eclipse for free, and its functions are very powerful. Now you can download Eclipse.

   IText API: Close Observation

Com. lowagie. text. Document is the main class for generating PDF files. It is the first class to be used. Once a document is created, a writer is required to write content to the document. Com.lowagie.text.html. writable writer is a PDF writer. The following lists the commonly used classes:

Com. lowagie. text. Paragraph -- this class indicates an indented section.

Com. lowagie. text. Chapter -- this class represents the Chapter in the PDF document. Use Paragraph as the question and use int as the chapter number to create it.

Com. lowagie. text. Font -- this class contains all the Font specifications, such as Font, size, style, and color. All fonts are declared as static constants in this class.

Com. lowagie. text. List -- this class represents a List, which contains many ListItems in order.

Com. lowagie. text. Table -- this class indicates tables containing cells, which are arranged in a matrix in an orderly manner.

Download iText and configure it in Eclipse

As a pure Java library, iText appears in the form of a JAR file (see references ). Once you download this library (under the path C: \ temp), perform the following steps to configure the iText library in the Eclipse environment:

Create a new Java project in Eclipse and name it iText.

In the Package Explorer view, right-click the iText project and select Properties.

Click Java Build Path. On the Libraries tab, click Add External JARs.

Browse to the C: \ temp directory and select the itext-1.3.jar under that directory.

Click OK.

Now that iText is configured, Eclipse is ready to create a Java application to generate a dynamic PDF file.

   Sample Application

What else can demonstrate the technology better than creating a working example by yourself? Now that you have the required tools (Eclipse IDE) and Libraries (iText Library), you can design and develop a sample application.

Let's create a simple PDF document that contains some basic elements, such as plain text, non-default color text, tables, lists, chapters, and sections. The purpose of this application is to familiarize you with the use of the iText library. There are many classes related to helping generate PDF documents. It is not possible to introduce all these classes here. The javadoc of iText is a good introduction to how to use these classes. Let's start coding.

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

Listing 1. instantiate a Document Object

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

The first parameter is the page size. The following parameters are left, right, top, and bottom margins. The document type is not defined yet. It depends on the type of the writer created. For our example, select com.lowagie.text=. analyze writer. Other writers include HtmlWriter, RtfWriter, and XmlWriter. Their names explain their actual use.

List 2. Create an external writer object

Response writer = Response writer. getInstance (document ,\
New FileOutputStream ("C :\\ ITextTest.pdf "));
Document. open ();

The first parameter is a reference to the document object, and the second parameter is the actual name of the file. The output path is also provided in the name. Next, open the document to write the content.
Now, you will add some text on the first page of the document. Use com. lowagie. text. Paragraph to add text. You can use text and its default font, color, size, and other settings to create a default section. Alternatively, you can set your own font. Let's take a look at these two practices.

Listing 3. Creating paragraph objects

Document. add (new Paragraph ("First page of the document ."));
Document. add (new Paragraph ("Some more text o ­ n \
First page with different color and font type .",
FontFactory. getFont (FontFactory. COURIER, 14, Font. BOLD, new Color (255,150,200 ))));

The following is an output example of the above Code. Add document. close (); at the end of the above Code to close the document.




(400) {this. resized = true; this. width = 400; this. alt = 'click here to open new window';} "onmouseover =" if (this. resized) this. style. cursor = 'hand'; "onclick =" window. open ('HTTP: // dev.yesky.com/imagelist/06/04/8hc192wxbtr7.gif'); ">

Figure 1. Output example of the above Code

You have seen how to add plain text to a PDF document. Next, you need to add some complex elements to the document. Create a new chapter. A section is a special section. By default, a chapter starts from a new page and displays a default number.

Listing 4. Create a 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 above Code, a new Chapter object, chapter1, is created with the title "This is Chapter 1". Setting the number level to 0 will not display the Chapter number on the page.

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

Listing 5. Create a 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 3X2 table .");
Section1.add (someSectionText );

Before adding a table, let's take a look at the document. Add the following two lines of code to close the document, compile and execute the program to generate the PDF document: document. add (chapter1); document. close ();.




(400) {this. resized = true; this. width = 400; this. alt = 'click here to open new window';} "onmouseover =" if (this. resized) this. style. cursor = 'hand'; "onclick =" window. open ('HTTP: // dev.yesky.com/imagelist/06/04/3s4o8z3j69pk.gif'); ">

Figure 2. Chapter output example

Next, create a table object. Create a table containing the row and column matrices. Cells in a row can span multiple columns. Similarly, cells in a column can span multiple rows. Therefore, a 3x2 table does not necessarily have 6 cells.

Listing 6. Create a 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, a table object t is created, which has three columns and two rows. Set the border color of the table. Fill is used to set the interval between Chinese cells and the boundary of cells. The interval refers to the border between adjacent cells. Next, three cell objects are created, and the text in each cell is different. Next, add them to the table. Add them to the first row and move them from the first column to the next column in the same row. Once this row is created, the next cell is added to the first column of the next row. You can also add cells to a table by providing only the text of cells, for example, t. addCell ("1.1 ");. Finally, add the table object to the section object.

Finally, let's take a look at how to add the list to the PDF document. The list contains a certain number of listitems. The list can be numbered or not numbered. Setting the first parameter to true indicates that you want to create a list of numbers.

Listing 7. Create a 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 have added the required object to the chapter1 object. Therefore, no other elements to be added to chapter1 can be added to the main document. As in the sample application, you must close the Document Object at this time.

Listing 8. Add a chapter to the main document

Document. add (chapter1 );
Document. close ();

   Run the sample application

Download the sample application, j-itextsample.jar (see download ).

Decompress the j-itextsample.jar in a directory. For example, if you extract the package to C: \ temp, the source code and class files will be put under the C: \ temp \ com \ itext \ test directory.

Open a command prompt and change the directory to C: \ temp.

Set the system class path in the command prompt. Include C: \ temp \ itext-1.3.jar in the system's class path. In Windows? Run the command set classpath = C: \ temp \ itext-1.3.jar; % classpath %.

Run java com. itext. test. ITextTest to run the application.

The program will generate an ITextTest.pdf document in the C: \ directory. The screen on the second page of this PDF document is shown below.




(400) {this. resized = true; this. width = 400; this. alt = 'click here to open new window';} "onmouseover =" if (this. resized) this. style. cursor = 'hand'; "onclick =" window. open ('HTTP: // dev.yesky.com/imagelist/06/04/cz2u1mlz4354.gif'); ">

Figure 3. PDF document Screen

   Conclusion

You have seen some basic elements for generating PDF files. The beauty of iText is that the syntax of the same element can be used by different types of writers. In addition, the writer's output can be redirected to the console (when the writer type is XML and HTML) and the servlet's output stream (when responding to the Web request of the PDF document) or other types of OutputStream. When the response is the same, but its type varies with the requested PDF, RTF, HTML, or XML document, it is very convenient to use iText. IText allows users to create watermarks, encrypt documents, and set other output details.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.