Two open-source tools for Java to dynamically generate PDF-itext and fop

Source: Internet
Author: User
Tags format definition xsl xslt

This article from http://www.blogjava.net/sean/archive/2008/10/05/232577.html

Due to work needs, today I briefly read the relevant documents about Java PDF generation. In summary, in addition to using the reporting platform and OOO's ancillary tools, there are currently two common approaches: itext and Apache fop. From the actual situation, let's take a look at the specific usage of the two processing PDF files with Chinese characters.

[Itext](Link)

I think many people have heard about itext. jasperreports's default PDF support comes from this software package, which features fast processing and many "advanced" pdf features, such: annotations, terraforms, digital signatures, encryption, and so on. It supports processing existing PDF files through itextasian. jar and itextasiancmaps. jar, which also supports Chinese characters. The disadvantage is that Java code is relatively dependent and you need to learn a lot of proprietary APIs. When the input/output formats change, you need to modify the code (unless you manually write some wrapper), which is not flexible enough. The current version is 2.1.3. Code:

Formatter. Java

1 import java. Io. fileoutputstream;
2
3 Import com. lowagie. Text. Document;
4 Import com. lowagie. Text. Font;
5 import com. lowagie. Text. pagesize;
6 Import com. lowagie. Text. Paragraph;
7 Import com.lowagie.text=. basefont;
8 Import com.lowagie.textdetail. Analyze writer;
9
10 public class formatter {
11
12 public static void main (string [] ARGs) throws exception {
13 document = new document (pagesize. A4 );
14 try {
15 system. Out. Print ("generating pdf ");
16 bytes writer. getinstance (document, new fileoutputstream ("test.pdf "));
17 document. open ();
18 // The Chinese font of itext
19 basefont bf1 = basefont. createfont ("stsong-light", "UniGB-UCS2-H", basefont. not_embedded );
20 // Custom font
21 basefont bf2 = basefont. createfont ("wqy-zenhei.ttf", basefont. identity_h, basefont. not_embedded );
22 Font font = new font (bf2, 12, Font. Normal );
23 paragraph P = new paragraph ("test ABC Chinese 123", font );
24 document. Add (P );
25 system. Out. println ("done .");
26} finally {
27 document. Close ();
28}
29}
30
31}

Effect:

Chinese supports stsong-light fonts by default. However, to optimize the output, the font of wenquanyi zhenghei is used here. If no Chinese font is specified, Chinese characters are not displayed by default.

[Fop](Link)

FOP is from Apache and appears relatively low on major Java websites and forums. I also touched it from the docbook line, docbook mainly provides a ready-made, in line with the general technical requirements of the data structure, and the display effect (such as PDF), is achieved through a predefined XSL-FO. XSL-FO is W3C standard, officially named XSL, one of the three major components/languages related to XSL, and the other two are XSLT and XPath. Apache FOP is one of the many proecessor processing fo. Compared with itext, fop supports more output formats and supports W3C standards. format definition can be completely separated from specific Java code, flexible and highly controllable. The disadvantage is that the performance is poor when the data volume is large, and the default Chinese support is poor. The current version is 0.95. Code:

Test. xml 1 <? XML version = "1.0" encoding = "UTF-8"?>
2 <source>
3 <title>
4 fop sample
5 </title>
6 <Paragraph>
7 test ABC Chinese 123
8 </Paragraph>
9 </source>

Test. XSL 1 <? XML version = "1.0" encoding = "UTF-8"?>
2 <XSL: Transform version = "1.0"
3 xmlns: XSL = "http://www.w3.org/1999/XSL/Transform"
4 xmlns: fo = "http://www.w3.org/1999/XSL/Format">
5
6 <XSL: template match = "/">
7 <FO: root>
8 <FO: Layout-master-set>
9 <FO: simple-page-master-name = "A4-portrait"
10 page-Height = "29.7" Page-width = "21.0" margin = "2 cm">
11 <FO: Region-body/>
12 </FO: simple-page-master>
13 </FO: Layout-master-set>
14 <FO: page-sequence master-reference = "A4-portrait">
15 <FO: Flow flow-name = "XSL-region-Body">
16 <FO: block font-family = "wenquanyi Zen Hei" font-size = "24pt">
17 <XSL: value-of select = "Source/Title"/>
18 </FO: block>
19 <FO: block font-family = "wenquanyi Zen Hei" text-indent = "1 cm">
20 <XSL: value-of select = "Source/Paragraph"/>
21 </FO: block>
22 </FO: flow>
23 </FO: page-sequence>
24 </FO: root>
25 </XSL: Template>
26
27 </XSL: Transform>

Fop-config.xml 1 <? XML version = "1.0"?>
2 <fop version = "1.0">
3 <base>. </base>
4 <source-resolution> 72 </source-resolution>
5 <target-resolution> 72 </Target-resolution>
6 <default-page-settings Height = "29.7 cm" width = "21.0 cm"/>
7 <renderers>
8 <Renderer mime = "application/pdf">
9 <filterlist>
10 <value> flate </value>
11 </filterlist>
12 <fonts>
13 <directory>. </directory>
14 <auto-detect/>
15 </fonts>
16 </Renderer>
17 </renderers>
18 </fop>

Formatter. Java 1 import java. Io. file;
2 Import java. Io. fileoutputstream;
3 Import java. Io. outputstream;
4
5 import javax. xml. Transform. result;
6 Import javax. xml. Transform. source;
7 Import javax. xml. Transform. transformer;
8 Import javax. xml. Transform. transformerfactory;
9 Import javax. xml. Transform. Sax. saxresult;
10 Import javax. xml. Transform. Stream. streamsource;
11
12 Import org. Apache. fop. Apps. fouseragent;
13 Import org. Apache. fop. Apps. fop;
14 Import org. Apache. fop. Apps. fopfactory;
15 Import org. Apache. fop. Apps. mimeconstants;
16
17 public class formatter {
18
19 public static void main (string [] ARGs) throws exception {
20 File Source = new file ("test. xml ");
21 file specs = new file ("test. XSL ");
22 file target = new file ("testbench ");
23 fopfactory = fopfactory. newinstance ();
24 fopfactory. setuserconfig ("fop-config.xml"); // read custom configuration
25 fouseragent = fopfactory. newfouseragent ();
26 outputstream out = new fileoutputstream (target );
27 out = new java. Io. bufferedoutputstream (out );
28 try {
29 system. Out. Print ("generating pdf ");
30 fop = fopfactory. newfop (mimeconstants. mime_pdf, fouseragent, out );
31 transformerfactory factory = transformerfactory. newinstance ();
32 transformer = factory. newtransformer (New streamsource (specs ));
33 source src = new streamsource (source );
34 result res = new saxresult (FOP. getdefaulthandler ());
35 transformer. Transform (SRC, Res );
36 system. Out. println ("done .");
37} finally {
38 out. Close ();
39}
40}
41
42}

Effect:

FOP supports Chinese characters (in fact, it supports custom fonts). Prior to version 0.94, it was very limited to generate a metrics file for every TrueType font to be used, in versions 0.94 and later, this requirement is not required and the system font and TTF font in the specified folder can be automatically scanned. If the Chinese font is not configured, Chinese characters are converted to "#" in PDF by default "#".

Although the sample code above is simple, it shows that fop is really powerful, that is, control. Limited space here, not all features are involved one by one, this simple example at least let us see from the original XML format of data, through XSLT according to custom rules into XSL-FO, the process of output to PDF can be strictly controlled out of Java code.

The above is my arrangement of some basic features and usage of itext and FOP. They have their own characteristics. You can continue to study them based on your own needs. The combination of fop and itext is not a problem. Hope to help friends in need.

Related Article

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.