Generate PDF files dynamically from Java applications

Source: Internet
Author: User
Tags border color contains include first row
Pdf| Program | Dynamic If your application needs to dynamically generate a PDF document, you need to iText the library. The Open source IText library enables the creation of PDF documents to be completed in an instant. This article describes IText and provides a use for it from Java? A technical application generates a guide to the more than a PDF document. We created a sample application to better understand IText.

Many applications require a PDF document to be generated dynamically. Such applications include bank generated customer reports for e-mail delivery to readers who purchase specific book chapters and receive them in PDF format. There are a lot of examples listed below. In this article, you will use the IText Java Library to build a PDF document and guide you through a sample application that enables you to better understand and use IText.

   familiar with IText

IText is a free Java library for the lowagie.com site (see Resources). The IText library is powerful enough to support the generation of HTML, RTF, and XML documents, as well as the ability to generate PDF documents. You can select the font used in the document from a variety of fonts. Also, the ITEXT structure allows you to generate any of these types of documents using the same code.

Classes in the IText library are used to generate PDF text in a variety of fonts, to generate tables in a PDF document, to add watermarks to pages, and so on. IText also offers many features. In an article it is impossible to one by one demo. The basic requirements for building PDF documents are described in this article.

We will use Eclipse for sample application development. As an open source IDE, Eclipse is available for free, and its functionality is very powerful. You can download Eclipse now.

  iText API: Close-range observation

Com.lowagie.text.Document is the main class that generates PDFs. It is the first class that needs to be used. Once you start creating a document, you will need a writer to write to the document. Com.lowagie.text.pdf.PdfWriter is a PDF recorder. The following lists the classes that you typically need to use:

com.lowagie.text.paragraph--This class represents an indented paragraph.

com.lowagie.text.chapter--This class represents the chapters in a PDF document. Use Paragraph as a topic 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. The various fonts are declared as static constants in this class.

com.lowagie.text.list--This class represents a list that contains many listitems in order.

com.lowagie.text.table--This class represents a table that contains cells, and the cells are arranged in an orderly manner in the matrix.

   Download IText and configure in Eclipse

As a pure Java library, IText is in the form of a JAR file (see Resources). Once you have downloaded the 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.

Right-click the IText item in the Package Explorer view and select Properties.

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

Browse to the C:\temp directory and select the Itext-1.3.jar in the directory.

Click OK.

Now that the ITEXT,ECLIPSE is configured, you are ready to create a Java application to generate a dynamic PDF document.

   Sample Application

What better way to demonstrate technology than to create a working example yourself? Now that you have the tools you need (the Eclipse IDE) and the library (IText library), you can start designing and developing a sample application.

Let's create a simple PDF document that contains basic elements such as plain text, color text for non-default fonts, tables, lists, chapters, and bars. The purpose of this application is to familiarize you with how the IText library is used. There are a number of classes that are related to helping to generate PDF documents. It is not possible to introduce all these classes here. IText's Javadoc is a good source of information about how to use these classes. Now let's start writing code.

The first step is to create a document. A document is a container for all the 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 parameters are left, right, top, and bottom margins. However, the type of the document has not been defined yet. It depends on the type of writer you are creating. For our example, the Com.lowagie.text.pdf.PdfWriter is selected. Other writers are HTMLWriter, Rtfwriter, XmlWriter, and so on. Their names explain their actual use.

Listing 2. Creating PDFWriter objects

PDFWriter writer = pdfwriter.getinstance (document, \
New FileOutputStream ("C:\\itexttest.pdf"));
Document.open ();


The first parameter is a reference to the Document object, the second parameter is the actual name of the file, and its output path is also given in that name. Next, open the document to write to the content.

You will now add some text to the first page of the document. Add text by Com.lowagie.text.Paragraph. You can create a default paragraph with the text and its default font, color, size, and so on. Alternatively, you can set your own font. Let's take a look at both of these approaches below.

Listing 3. Create a Paragraph object

Document.add (New Paragraph ("the document.");
Document.add (New Paragraph ("Some more text on" \
The I-page with different color and font type. ",
Fontfactory.getfont (Fontfactory.courier, Font.Bold, New Color (255, 150, 200)));
The following is an example of the output from the above code. Add Document.close () at the end of the code above; To close the document.


Figure 1. Sample output from the above code
You've seen how to add plain text to a PDF document. Next, you need to add some complex elements to your document. We started to create a new chapter. Chapters are a special section, by default, chapters start with a new page and display a default number.

Listing 4. Create a Chapter Object

Paragraph title1 = new Paragraph ("Chapter 1",
Fontfactory.getfont (Fontfactory.helvetica, \
Font.bolditalic, New Color (0, 0, 255));
Chapter chapter1 = new Chapter (title1, 1);
Chapter1.setnumberdepth (0);
In the above code, a new chapter object is created, Chapter1, with the title "This is Chapter 1", and setting the numbering level to 0 does not display the chapter number on the page.

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

Listing 5. Create a subsection object

Paragraph title11 = new Paragraph ("This are 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 adding a table, let's look at the document. Add the following two lines of code to close the document, and then compile and execute the program to generate the PDF document: Document.add (chapter1);d ocument.close ();.


Figure 2. Chapter Output Example
Next, create a Table object. Create a table that contains a row and column matrix. Cells in a row can span multiple columns. Similarly, cells in a column can span multiple rows. Therefore, a table of 3 x 2 does not actually 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, you create a Table object, T, which has three columns and two rows. Then set the border color of the table. Padding is used to set the spacing between text in a cell and the bounds of the cell. An interval refers to the boundary between adjacent cells. Next, you will create three cell objects with different text in each cell. Next, add them to the table. Add them to the first row, starting with the first column and moving to the next column in the same row. Once the row is created, the next cell is added to the first column in the next line. You can also add cells to a table by providing only the text of a cell, for example, T.addcell ("1.1");. Finally, you add the Table object to the Section object.

Finally, let's take a look at how to add a list to a PDF document. The list contains a certain number of ListItem. You can either number or not number the list. Setting the first argument to TRUE indicates that you want to create a list to be numbered.

Listing 7. Create a List Object

List L = new List (true, false, 10);
L.add (New ListItem ("A list of the");
L.add ("Second Item of List") (new ListItem);
Section1.add (l);
We have added the desired object to the Chapter1 object. Therefore, there are no more elements to add to the Chapter1, and you can now add Chapter1 to the main document. As you do in the sample application, you also close the Document object at this point.

Listing 8. Add chapters to the main document

Document.add (Chapter1);
Document.close ();
   running the sample application

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

Unzip the J-itextsample.jar in a directory. For example, if you unzip it to C:\temp, the source and class files will be placed in the C:\temp\com\itext\test directory.

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

Set the system's classpath in this command prompt. Include C:\temp\itext-1.3.jar in the system's classpath. In Windows? , execute the command set classpath=c:\temp\itext-1.3.jar;%classpath%.

Run the application using the command Java com.itext.test.ITextTest.

The program will be C:\ A itexttest.pdf document is generated under the directory. The screen diagram for the second page of this PDF document is shown below.


Figure 3. Screen map of PDF document
   Concluding remarks

You've seen some basic elements that generate PDFs. The beauty of IText is that the syntax of the same element can be used by different types of writers. Also, the output of the writer can be redirected to the console (when the writer type is XML and HTML), the servlet's output stream (when responding to a WEB request for a PDF document), or other types of outputstream. It is convenient to use IText when the response is the same, but its type differs depending on the requested PDF, RTF, HTML, or XML document. 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.