iText生成PDF入门

来源:互联网 发布:长沙最新cnc编程招聘 编辑:程序博客网 时间:2024/06/11 01:42

目录:

  1. 介绍
  2. 实验环境
  3. 入门示例

[一]、介绍

iText是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF文档,而且可以将HTML网页转化为PDF文件,同时它可以很方便的和web或者其他应用整合使用。

iText 官网:http://www.itextpdf.com/

HTML转换为PDF需要xmlworker :http://sourceforge.net/projects/xmlworker

其他注意点:

  • 如果需要自己编译iText包,需要用到第三方的jar:bcprov、bcmail 、bctsp.
  • 如果用到中文,需要CJK字体的扩展包:iTextAsian.jar
  • 如果用到特殊符号的,需要另一个扩展包:itext-hyph-xml.jar. 
  • 上述提到的所有lib包,都包含在它的发布版本里。

[二]、实验环境

  • java version “1.6.0_18″
  • iText 5.3.2

[三]、入门示例

Java代码:DemoMyFirstPDF.java

1package com.micmiu.pdf.itext;
2 
3import java.io.FileOutputStream;
4 
5import com.itextpdf.text.BaseColor;
6import com.itextpdf.text.Chunk;
7import com.itextpdf.text.Document;
8import com.itextpdf.text.Font;
9import com.itextpdf.text.PageSize;
10import com.itextpdf.text.Paragraph;
11import com.itextpdf.text.pdf.BaseFont;
12import com.itextpdf.text.pdf.PdfWriter;
13 
14/**
15 *
16 * @author <a href="http://www.micmiu.com">Michael Sun</a>
17 */
18public class DemoMyFirstPDF {
19 
20    /**
21     * @param args
22     */
23    public static void main(String[] args) throws Exception {
24        String pdfPath = "d:/test/itext/demo-first.pdf";
25        createFirstPDF(pdfPath);
26    }
27 
28    public static void createFirstPDF(String pdfPath) throws Exception {
29        // 第一步: Create a Document
30        Document document = new Document(PageSize.A4);
31        // 第二 步: Get a PdfWriter instance.
32        PdfWriter.getInstance(document, newFileOutputStream(pdfPath));
33        // 第三步:Open the Document.
34        document.open();
35 
36        // 添加Meta信息
37        document.addAuthor("Michael Sun");
38        document.addCreator("Michael Sun");
39        document.addTitle("Michael的技术博客");
40        document.addSubject("技术博客");
41        document.addCreationDate();
42        document.addKeywords("开源技术,企业架构,集群,负载均衡,分布式,J2EE,Java,SSH");
43 
44        // 添加Header信息
45        document.addHeader("blog""http://www.micmiu.com");
46        document.addHeader("twitter""@suncto");
47        document.addHeader("weibo""http://weibo.com/ctosun");
48        document.addHeader("mail""sjsky007@gmail.coom");
49 
50        // 第四步:添加内容
51 
52        // 添加 Paragraph
53        document.add(new Paragraph("Hello iText."));
54 
55        document.add(Chunk.NEWLINE);
56 
57        // 添加 中文信息
58        BaseFont bfCN = BaseFont.createFont("STSongStd-Light""UniGB-UCS2-H",
59                false);
60        Font fontCN = new Font(bfCN, 12, Font.NORMAL, BaseColor.BLUE);
61        document.add(new Paragraph("这是中文:欢迎来到iText世界。", fontCN));
62 
63        // 第五步:Close the Document.
64        document.close();
65    }
66 
67}

运行后生成的PDF文件如下:

转自:http://www.micmiu.com/opensource/expdoc/itext-pdf-demo/

原创粉丝点击