Many applications require dynamic generation of PDF documents. These applications cover readers who generate customer statements and deliver them via e-mail to purchase specific book chapters and receive these book chapters in PDF format. The list is endless. In this article, we will use the IText Java library to generate PDF documents. We'll show you a sample application so that you can do it yourself and get a better understanding of it.
Familiar with IText V5.3.0 version
IText is a Java library that can be obtained free of charge from http://itextpdf.com/(see Resources). The IText library is very powerful and supports generating HTML, RTF, and XML documents, and also supports the generation of PDF documents. You can choose from a wide variety of fonts to use in your documents. In addition, the ITEXT structure allows you to use the same code to generate any type of document mentioned above.
The IText library contains classes that generate PDF text using a variety of fonts, generate tables in PDF documents, add watermarks to pages, and so on. IText also offers a number of other features. All of these features cannot be demonstrated in an article. We'll cover the basics needed to generate PDFs. For more details, see the documentation provided by your vendor (see Resources).
We will use Eclipse to develop our sample application. It is free and very powerful as an open source ide,eclipse. You can download Eclipse now (see Resources).
IText API: Learn more about
Com.itextpdf.text.Document is the primary class used to generate PDF documents. This is the first class that needs to be instantiated. After you create a document, you need a writer to write information to it. Com.itextpdf.text.pdf.PdfWriter is a PDF writer. Some other common classes are provided below:
- com.itextpdf.text.Paragraph: This class represents an indented paragraph.
- Com.itextpdf.text.Chapter: This class represents a chapter in a PDF document. Use
Paragraph as a title, int as a chapter number to create the class.
- Com.itextpdf.text.Font: This class contains all the specifications for a font, such as the font set, font size, style, and color. Various fonts are declared as static constants in this class.
- com.itextpdf.text.List: This class represents a list, which in turn contains many
ListItems .
- com.itextpdf.text.pdf.PDFPTable: This is a table that can be placed in an absolute position or as a class table to be added to a document.
- com.itextpdf.text.Anchor: A Anchor may be a reference, or a reference target.
Download and configure IText in Eclipse
As a pure Java library, IText is provided as a JAR file (see Resources). After downloading the library (assuming download to path C:\temp), use the following steps to configure the IText library in the ECLIPSE environment:
- Create a new Java project named IText in Eclipse.
- Right-click the IText project in the Package Explorer view and select Properties.
- Click Java Build Path. On the Libraries tab, click Add External JARs.
- Locate the C:\temp directory and select Itext-5.3.0.jar in this directory.
- Click OK.
IText is now configured, and Eclipse is ready to create Java applications to generate dynamic PDF documents.
Back to top of page
Sample Application
What better way to demonstrate any technology than a valid example you've created yourself? Now that you have the tools (Eclipse IDE) and library (IText library) You need, we are ready to design and develop an effective sample program.
Start by creating a simple PDF document that contains some basic elements, such as plain text, colored text with non-default fonts, tables, lists, chapters, sections, and so on. The purpose of this application is to familiarize you with the way you use the IText library. There are a number of classes that perform a lot of work related to PDF document generation. All these classes are not possible in this article. IText's Javadocs is a good source of information about how to use these classes. Next we start coding.
The first step is to create a document. A document is a container for all elements of a PDF document.
Listing 1. Instantiating a Document object
Document document = new Document (PAGESIZE.A4, 50, 50, 50, 50);
The first parameter is the page size. The next few parameters are the left margin, the right margin, the top margin, and the bottom margin, respectively. The type of this document is not yet defined. It relies on the type of writer you create. For our example, we choose Com.itextpdf.text.pdf.PdfWriter. Other writers include HTMLWriter, Rtfwriter, XmlWriter, and so on. Their names illustrate their actual use.
Listing 2. Create a PDFWriter object
PDFWriter writer = pdfwriter.getinstance (document, New FileOutputStream ("C:\\itexttest.pdf"));d Ocument.open ();
The first parameter is a reference to the Document object, and the second parameter is the absolute name of the file to which the output will be written. Next, we open the document and start writing.
Now we'll add some text to the first page of the document. Any text is added with the help of Com.itextpdf.text.Paragraph. You can create a default paragraph with your text and default settings such as font, color, font size, and so on. Otherwise, you can provide your own fonts. In this article, we'll also discuss the locator (link) for the PDF document. In this PDF, we use BackToTop as a link. When you click the BackToTop link, it takes you to the first page of the document. You need to set the text as the target for the first page. Let's see how to set the targeting and font to the added paragraphs.
Listing 3. Create a Paragraph object
Anchor anchortarget = new Anchor ("first page of the document."); Anchortarget.setname ("BackToTop"); Paragraph paragraph1 = new Paragraph (); Paragraph1.setspacingbefore (+); Paragraph1.add (anchortarget); Document.add (PARAGRAPH1);d Ocument.add (New Paragraph ("Some more text in the first page with different color and font type.") , Fontfactory.getfont (Fontfactory.courier, font.bold,new, Cmykcolor (0, 255, 0, 0)));
Figure 1 shows a sample output of the code in Listing 3. To close the document, document.close(); add it to the end of the code in Listing 3.
Figure 1. Sample output from the code in Listing 3
You just saw how to add plain text to a PDF document. Next, we need to add some complex elements to the document. First create a new chapter. Chapter is a special section that starts with a new page and displays a number by default.
Listing 4. Create a Chapter Object
Paragraph title1 = new Paragraph ("Chapter 1", Fontfactory.getfont (Fontfactory.helvetica, font.bolditalic , new Cmykcolor (0, 255, 255,17)); Chapter chapter1 = new Chapter (title1, 1); Chapter1.setnumberdepth (0);
In the code in Listing 4, we created a new chapter object chapter1 titled "This is Chapter 1". Set the numbering depth to 0so that the chapter number is not displayed on the page.
A section is a child element of a chapter. In the code in Listing 5, we create a section with the title "This is the 1 in Chapter 1". To add some text to this section, we create another paragraph object someSectionText and add it to the Stanza object.
Listing 5. Create a Section Object
Paragraph title11 = new Paragraph ("This was section 1 in Chapter 1", Fontfactory.getfont (Fontfactory.helvetica, +, Fon T.bold, New Cmykcolor (0, 255, 255,17)); Section Section1 = chapter1.addsection (TITLE11); Paragraph somesectiontext = new Paragraph ("This text comes as part of the section 1 of Chapter 1."); Section1.add (somesectiontext); somesectiontext = new Paragraph ("Following is a 3 X 2 table."); Section1.add (Somesectiontext);
Before you add a table, let's look at what the document looks like. Add the following two lines of code to close the document in Figure 2. Then compile and execute the program to generate the PDF document: document.add(chapter1);document.close(); .
Figure 2. Sample output of the chapter
Next, we'll create a Table object. A table contains a matrix of rows and columns. One cell in a row can occupy more than one column. Similarly, a cell in a column can occupy more than one row.
Listing 6. Create a Table object
Pdfptable t = new pdfptable (3); T.setspacingbefore (+); T.setspacingafter (+); Pdfpcell C1 = new Pdfpcell (New Phrase ("Header1")); T.addcell (C1); Pdfpcell C2 = new Pdfpcell (New Phrase ("Header2")); T.addcell (C2); Pdfpcell C3 = New Pdfpcell (New Phrase ("Header3")); T.addcell (C3); T.addcell ("1.1"); T.addcell ("1.2"); T.addcell ("1.3"); Section1.add (t);
In the code in Listing 6, we created a Pdfptable object t that contains 3 columns and continues to add rows. Next, we create 3 Pdfpcell objects, each containing a different text. We are constantly adding them to the table. They are added to the first row, starting at the first column, and moving to the next column in the same row. When the line is complete, add the next cell to the first column in the next row. It can also be added to a table by providing the text of the cell, for example t.addCell("1.1"); . Finally, the table object is added to the Section object.
Finally, let's look at how to add a list to a PDF document. The list contains more than one ListItem . A list can be numbered or no numbering. Passing the first argument as true indicates that you want to create a numbered list.
Listing 7. To create a list object
List L = new List (true, False,), L.add (New ListItem ("First item of List")), L.add (New ListItem ("Second Item of List"); SE Ction1.add (l);
We have added all of the content to the chapter1 object. Now we add an image to the Java object. We can scale an image using one of the following image methods:
- Scaleabsolute ()
- Scaleabsolutewidth ()
- Scaleabsoluteheight ()
- Scalepercentage ()
- Scaletofit ()
In Listing 8, we used the Scaleabsolute. The image object is then added to the section.
Listing 8. Add an Image to the main Document
Image image2 = image.getinstance ("ibmlogo.bmp"); Image2.scaleabsolute (120f, 120f); Section1.add (Image2);
The Com.itextpdf.text.Anchor class in IText represents a link inside an external Web site or document. A locator (link) can be clicked like a link in a Web page. To add a locator, we need to create a new locator and set the reference to the Anchor target created in Listing 3. You then add the locator to the section and add the section to the document.
Listing 9. Add a locator to the main document
Paragraph title2 = new Paragraph ("Using Anchor", Fontfactory.getfont (Fontfactory.helvetica, + , Font.Bold , New Cmykcolor (0, 255, 0, 0)); Section1.add (title2); Title2.setspacingbefore (5000); Anchor Anchor2 = new Anchor ("Back to Top"), Anchor2.setreference ("#BackToTop"); Section1.add (ANCHOR2);
There is no need to add to chapter1 the element in, it is chapter1 time to add to the master. document Here, when we complete the sample application, the Document object is also closed.
Listing 10. Add a chapter to the main document
Document.add (Chapter1);d ocument.close ();
Back to top of page
Run the sample application
- Download the sample application J-itextsample.jar (see download).
- Extract the J-itextsample.jar into a directory, for example, if you extract it to C:\temp, this will place the source code and the class file in C:\temp\com\itext\test.
- Open a command prompt, and change the directory to C:\temp.
- Set the classpath of your system at this command prompt. Will be
C:\temp\itext-5.3.0.jar included in the system's classpath. On Windows®, execute the command set classpath=C:\temp\itext-5.3.0.jar;%classpath% .
- Use the command to
java com.itext.test.ITextTest run the application.
The program will be in C \ The Itexttest.pdf document is generated in the Figure 3 shows the screen for the first page of the PDF document.
Figure 3. The screen of a PDF document
Figure 4 shows the 1th chapter in the PDF document and the screen of its sections, text, tables, lists, and images.
Figure 4. The screen of a PDF document
Figure 5 shows the screen of the Anchor link in the PDF document.
Figure 5. The screen of a PDF document
Conclusion
You've learned some of the basic elements involved in generating PDFs. The beauty of IText is that you can use the syntax of the same element in different types of writers. In addition, you can redirect the output of the writer to the console (for XML and HTML writers), the output stream of the servlet (in response to a WEB request to a PDF document), or any other type of output stream. IText can also be useful in situations where the response is the same, but the response type is different (PDF, RTF, HTML, or XML). IText allows you to create watermarks, encrypt documents, and other output details.
This article is reproduced from: http://www.ibm.com/developerworks/cn/opensource/os-javapdf/(if there is a violation of the reprint, please contact Bo Master)
JAVA Generate PDF report ()