iText介绍
iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。
项目要使用iText,必须引入jar包。才能使用,maven依赖如下:
转载:http://www.cnblogs.com/h--d/p/6150320.html1 <dependency> 2 <groupId>com.itextpdf</groupId> 3 <artifactId>itextpdf</artifactId> 4 <version>5.5.10</version> 5 </dependency>
输出中文,还要引入下面itext-asian.jar包:
1 <dependency> 2 <groupId>com.itextpdf</groupId> 3 <artifactId>itext-asian</artifactId> 4 <version>5.2.0</version> 5 </dependency>
设置pdf文件密码,还要引入下面bcprov-jdk15on.jar包:
1 <dependency> 2 <groupId>org.bouncycastle</groupId> 3 <artifactId>bcprov-jdk15on</artifactId> 4 <version>1.54</version> 5 </dependency>
iText常用类
- com.itextpdf.text.Document:这是iText库中最常用的类,它代表了一个pdf实例。如果你需要从零开始生成一个PDF文件,你需要使用这个Document类。首先创建(new)该实例,然后打开(open)它,并添加(add)内容,最后关闭(close)该实例,即可生成一个pdf文件。
- com.itextpdf.text.Paragraph:表示一个缩进的文本段落,在段落中,你可以设置对齐方式,缩进,段落前后间隔等。
- com.itextpdf.text.Chapter:表示PDF的一个章节,他通过一个Paragraph类型的标题和整形章数创建。
- com.itextpdf.text.Font:这个类包含了所有规范好的字体,包括family of font,大小,样式和颜色,所有这些字体都被声明为静态常量。
- com.itextpdf.text.List:表示一个列表;
- cocom.itextpdf.text.List:表示一个列表;
- com.itextpdf.text.Anchor:表示一个锚,类似于HTML页面的链接。
- com.itextpdf.text.pdf.PdfWriter:当这个PdfWriter被添加到PdfDocument后,所有添加到Document的内容将会写入到与文件或网络关联的输出流中。
- com.itextpdf.text.pdf.PdfReader:用于读取PDF文件;
iText使用
- 创建一个简单的pdf文件,如下:
1 package com.hd.pdf; 2 3 import java.io.FileNotFoundException; 4 import java.io.FileOutputStream; 5 6 import com.itextpdf.text.Document; 7 import com.itextpdf.text.DocumentException; 8 import com.itextpdf.text.Paragraph; 9 import com.itextpdf.text.pdf.PdfWriter; 10 11 public class TestPDFDemo1 { 12 13 public static void main(String[] args) throws FileNotFoundException, DocumentException { 14 15 // 1.新建document对象 16 Document document = new Document(); 17 18 // 2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。 19 // 创建 PdfWriter 对象 第一个参数是对文档对象的引用,第二个参数是文件的实际名称,在该名称中还会给出其输出路径。 20 PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:/Users/H__D/Desktop/test.pdf")); 21 22 // 3.打开文档 23 document.open(); 24 25 // 4.添加一个内容段落 26 document.add(new Paragraph("Hello World!")); 27 28 // 5.关闭文档 29 document.close(); 30 31 } 32 33 }
打开文件