Itext generate PDF file using Method Example servlet output PDF document method

Source: Internet
Author: User
Tags border color image png

First, the preface

In the Enterprise Information System, report processing has always been a relatively important role, this article will introduce a PDF report to generate a Java component--itext. By using JSP or JavaBean to generate PDF reports on the server side, the client uses hyperlinks to display or download the generated report, which solves the problem of the B/s system's report processing.

  Ii. introduction of Itext

Itext is a well-known open source site SourceForge a project that is used to generate a PDF document of a Java class library. Not only can you generate PDF or RTF documents through Itext, but you can convert XML and HTML files to PDF files.

IText installation is very convenient, in the Http://www.lowagie.com/iText/download.html-download The Web site download Itext.jar file, only in the system classpath add Itext.jar Path, in the program can use the Itext class library.

  Third, the establishment of the first PDF document

It takes 5 steps to build a PDF document with Itext:

① establishes an instance of the Com.lowagie.text.Document object.

Document document = new document ();

② establishes a writer (Writer) that is associated with the document object and can write documents to disk through the writer (Writer).

Pdfwriter.getinstance (document, New FileOutputStream ("Helloworld.pdf"));

③ Open the document.

Document.open ();

④ add content to your document.

Document.add (New Paragraph ("Hello World"));

⑤ closes the document.

Document.close ();

With the 5 steps above, you can produce a helloworld.pdf file with the contents "Hello World".

Creating an instance of a Com.lowagie.text.Document object

There are three constructors for the Com.lowagie.text.Document object, respectively:

public Document ();
Public Document (Rectangle pageSize);
Public Document (Rectangle pageSize,
int MarginLeft,
int MarginRight,
int MarginTop,
int marginbottom);

The parameter PageSize of the constructor is the size of the document page, and for the first build function, the page size is A4, the same as that of document (PAGESIZE.A4); For the third build function, Parameters marginleft, MarginRight, MarginTop, MarginBottom, respectively, are left, right, top, and bottom margins.

Parameters pagesize can be used to set the page size, face background color, and page Landscape/portrait properties. Itext defines paper types such as A0-A10, AL, letter, Halfletter, _11x17, Ledger, note, b0-b5, Arch_a-arch_e, FLSA, and Flse, or through rectangle PageSize = new Rectangle (144, 720), custom paper. The rectangle method Rotate () enables you to set the page to landscape.

Writer (Writer) object

Once the Document object is established, you need to establish one or more writer (Writer) objects to associate with it. The writer (Writer) object allows you to save a specific document in a format that you want. If Com.lowagie.text.PDF.PDFWriter can save the document as a PDF file, Com.lowagie.text.html.HtmlWriter can save the document as an HTML file.

Set document properties

Before you open a document, you can set properties such as the title, subject, author, keyword, binding, creator, producer, date created, and so on for the document, and the method is called:

public boolean addtitle (String title)
public boolean addsubject (String subject)
public boolean addkeywords (String keywords)
public boolean Addauthor (String author)
public boolean addcreator (String creator)
public boolean addproducer ()
public boolean addcreationdate ()
public boolean AddHeader (string name, string content)

Where method AddHeader is not valid for PDF documents, AddHeader is only valid for HTML documents and is used to add header information for the document.
When the new page is generated, you can set the size of the page, bookmarks, footnotes (HeaderFooter) and other information, the method is called:

public boolean setpagesize (Rectangle pageSize)
Public boolean Add (Watermark watermark)
public void Removewatermark ()
public void SetHeader (HeaderFooter header)
public void Resetheader ()
public void Setfooter (HeaderFooter footer)
public void Resetfooter ()
public void Resetpagecount ()
public void Setpagecount (int pagen)

If you want to set page properties for the first page, these methods must be called before the document is opened.

For PDF documents, Itext also provides display properties for the document, by invoking the Setviewerpreferences method of the writer to control the display properties of Acrobat Reader when the document is opened, such as whether it is a single-page display, whether it is full-screen, and whether the status bar is hidden.

In addition, Itext also provides security for PDF files, through the writer (Writer) Setencryption method, you can set the document's user password, read-only, printable and other properties.

Add Document Content

All additions to the document are objects, such as phrase, Paragraph, Table, graphic objects, and so on. A more common paragraph (Paragraph) object is used to add a piece of text to a document.
Iv. Text Processing

Itext processes text with text blocks (Chunk), phrases (Phrase), and paragraphs (paragraph).
A text block (Chunk) is the smallest unit of text processing, consisting of a string of strings formatted (including font, color, size). As the following code produces a string with a font of Helvetica, size 10, underlined:

Chunk Chunk1 = new Chunk ("This text is underlined", Fontfactory.getfont (Fontfactory.helvetica, A, font.underline));

A phrase (Phrase) consists of one or more text blocks (Chunk), and a phrase (Phrase) can also set a font, but is not valid for text blocks (Chunk) that have a font set. By using the phrase (Phrase) member function Add, you can add a block of text (Chunk) to the phrase (Phrase), such as: Phrase6.add (Chunk);

A paragraph (paragraph) consists of one or more text blocks (Chunk) or phrases (Phrase), equivalent to the concept of paragraphs in a Word document, as well as setting the font size, color, and so on for a paragraph. You can also set the first line indent, alignment (left, right, and center) of the paragraph. You can set the alignment of a paragraph by function setalignment, Setalignment 1 is centered, 2 is right-aligned, 3 is left aligned, and the default is left.

  V. Table processing

The classes that work with tables in Itext are: Com.lowagie.text.Table and com.lowagie.text.PDF.PDFPTable, which can be com.lowagie.text.Table for simpler table processing, but if you want to handle complex tables, this requires to com.lowagie.text.PDF.PDFPTable for processing. Here is a description of the class com.lowagie.text.Table.

There are three constructors for class Com.lowagie.text.Table:

①table (int columns)
②table (int columns, int rows)
③table (Properties attributes)

The parameters columns, rows, and attributes are the number of columns, rows, and table properties of the table respectively. You must specify the number of columns in the table when you create the table, but you do not need to specify the number of rows.

After you have established the table, you can set properties such as border width, border color, padding (padding space, spacing between cells), and so on. The following is a simple example of how to use a table with the following code:

1:table table = new Table (3);
2:table.setborderwidth (1);
3:table.setbordercolor (New Color (0, 0, 255));
4:table.setpadding (5);
5:table.setspacing (5);
6:cell cell = new cell ("header");
7:cell.setheader (TRUE);
8:cell.setcolspan (3);
9:table.addcell (cell);
10:table.endheaders ();
11:cell = new cell ("Example cell with colspan 1 and rowspan 2");
12:cell.setrowspan (2);
13:cell.setbordercolor (New Color (255, 0, 0));
14:table.addcell (cell);
15:table.addcell ("1.1");
16:table.addcell ("2.1");
17:table.addcell ("1.2");
18:table.addcell ("2.2");
19:table.addcell ("Cell test1");
20:cell = new cell ("Big cell");
21:cell.setrowspan (2);
22:cell.setcolspan (2);
23:table.addcell (cell);
24:table.addcell ("Cell test2");

The results of the operation are as follows:

Header
Example cell with colspan 1 and rowspan 2 1.1 2.1
1.2 2.2
Cell Test1 Big cell
Cell Test2

The code 1-5 line is used to create a new table, as shown in the code, to create a table with a column number of 3 and to set the border width to 1, with a blue color and a padding of 5.

Code 6-10 lines are used to set the table header, line 7th Cell.setheader (TRUE), the cell is displayed as the header information, the 8th row is Cell.setcolspan (3), the cell is 3 columns, and the table header information is added to the table. Note that once the header information has been added, you must call the Endheaders () method, such as line 10th, otherwise the header information will not be displayed when the table spreads.

The Code 11-14 row is a cell that adds a width to the table and occupies two rows.

When you add cells (cell) to a table, you add them from left to right and from top to bottom. If you finish 11 lines of code, 2 rows of 2 columns are blank in the lower right of the table, which is when you add cells to the table, fill in the blanks first, and then another line, 15-24 lines of code that illustrate the order of additions.

  VI. Image processing

The class that handles tables in Itext is Com.lowagie.text.Image, and currently itext supports image formats such as GIF, Jpeg, PNG, WMF, and so on, for different image formats, Itext automatically recognize the image format with the same constructor. Obtain an instance of the GIF, JPG, and PNG images, respectively, with the following code.

Image gif = image.getinstance ("Vonnegut.gif");
Image jpeg = image.getinstance ("mykids.jpg");
Image png = image.getinstance ("Hitchcock.png");

Location of the image

The position of the image mainly refers to the alignment of the image in the document, the position of the image and the text. In Itext, the function public void setalignment (int alignment) is processed, and the parameter alignment is Image.right, Image.middle, and Image.left, respectively, to right align, center, Left-aligned, when the parameter alignment to Image.textwrap, image.underlying refers to the text around the graphic display, graphics as text background display. These two parameters can be combined to achieve the desired effect, such as setalignment (image.right| Image.textwrap) shows the image is right-aligned and the text is displayed around the image.

Dimensions and rotation of images

If the image is not displayed in the document in the original size, you can set it by using the following function:

public void Scaleabsolute (int newwidth, int newheight)
public void scalepercent (int percent)
public void scalepercent (int percentx, int percenty)

The function public void scaleabsolute (int newwidth, int newheight) sets the display dimension directly, the function public void scalepercent (int percent) sets the display scale, such as Scalepercent (50) indicates that the displayed size is 50% of the original size, while the function scalepercent (int percentx, int percenty) Displays the magnification of the image at a high width.

If the image needs to be rotated at a certain angle and displayed in the document, it can be set by the function public void setrotation (double R), the parameter r is radians, and the argument r= MATH.PI/6 if the rotation angle is 30 degrees.

  Seven, Chinese processing

The default Itext font settings do not support Chinese fonts, you need to download the Far East Font pack Itextasian.jar, otherwise you cannot export the Chinese font to the PDF document. You can use Chinese in your document with the following code:

Basefont Bfchinese = Basefont.createfont ("Stsong-light", "unigb-ucs2-h", basefont.not_embedded);
Com.lowagie.text.Font Fontchinese = new Com.lowagie.text.Font (Bfchinese, Com.lowagie.text.Font.NORMAL);
Paragraph pragraph=new Paragraph ("Hello", Fontchinese);

  Viii. Post-Total

Itext also has a lot of advanced features, here is not one of the introduction, the specific development can refer to the published documents. Overall, Itext is a good set of PDF components in a Java environment. Because Itext supports the development under Jsp/javabean, this makes the report problem of B/s application be solved well. Because Itext is not specifically for the production of report design, all reports in the content, format need to write code to achieve, compared to those who support the visual design of the professional report software, programming workload has a certain degree of increase.

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.