jar包为itext.jar,itextAsia.jar,最好都是最新的 ;
或maven引用:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.11</version>
</dependency>
<!-- 支持中文字体 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
生成PDF步骤:
- 创建文档对象实例
Document document = new Document();
- 建立书写器(Writer)与文档对象(document)关联,通过书写器将文档写入磁盘
PdfWriter writer = PdfWriter.getInstance(document,response.getOutputStream());
- 打开文档
document.open();
- 文档中添加内容
document.add(element);
其中的element可以为 Paragraph PdfPTable Image等,见详细分析
- 闭文档
document.close();
详细分析:
- 生成document对象实例:三种构造方法
public Document();
public Document(Rectangle pageSize);
public Document(Rectangle pageSize, float marginLeft, float marginRight,float marginTop, float marginBottom);
pageSize是指文档页面大小,public document();页面大小为A4,效果等同于Document(PageSize.A4);
marginLeft、marginRight、marginTop、marginBottom分别为左、右、上、下的页边距。
- 文档属性
在文档打开之前,可以设定文档的标题、主题、作者、关键字、创建者、生产者、创建日期等属性,调用的方法分别是:
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()
添加文档内容
所有向文档添加的内容都是以对象为单位的,如Phrase、Paragraph、Table、Graphic对象等。比较常用的是段落(Paragraph)对象,用于向文档中添加一段文字。
IText中用文本块(Chunk)、短语(Phrase)和段落(paragraph)处理文本。
- 文本块(Chunk)是处理文本的最小单位,有一串带格式(包括字体、颜色、大小)的字符串组成。
Chunk dimension_lable = new Chunk("Dimensions: ");
- 短语(Phrase)由一个或多个文本块(Chunk)组成,短语(Phrase)也可以设定字体,但对于其中以设定过字体的文本块(Chunk)无效。通过短语(Phrase)成员函数add可以将一个文本块(Chunk)加到短语(Phrase)中;
Phrase dimension = new Phrase(); dimension.add(dimension_lable);
- 段落(paragraph)由一个或多个文本块(Chunk)或短语(Phrase)组成,相当于WORD文档中的段落概念,同样可以设定段落的字体大小、颜色等属性。另外也可以设定段落的首行缩进、对齐方式(左对齐、右对齐、居中对齐)。通过函数setAlignment可以设定段落的对齐方式,默认为左对齐。
Paragraph ph= new Paragraph(); ph.add(dimension_lable); ph.add(dimension);
- Itext中处理表格在有PDFTable,Table。对于简单在表格处理可以用Table,但如果要处理复杂的表格就需要PDFTable进行处理。
创建表格时,必须要指定列,行则不是必须的。
建立表格之后,可以设定表格的属性,如:边框宽度、边框颜色、衬距(padding space 即单元格之间的间距)大小等属性。
- IText中处理图像的类为Image,目前iText支持的图像格式有:GIF, Jpeg, PNG, wmf等格式,对于不同的图像格式,iText用同样的构造函数自动识别图像格式。通过下面的代码分别获得gif、jpg、png图像的实例。
Image gif = Image.getInstance("vonnegut.gif");
Image jpeg = Image.getInstance("myKids.jpg");
Image png = Image.getInstance("hitchcock.png");
如果图像在文档中不按原尺寸显示,可以通过下面的函数进行设定:
- 函数public void scaleAbsolute(int newWidth, int newHeight)直接设定显示尺寸;
- 函数public void scalePercent(int percent)设定显示比例,如scalePercent(50)表示显示的大小为原尺寸的50%;
- 函数scalePercent(int percentX, int percentY)则图像高宽的显示比例。
中文/字体处理
默认的iText字体设置不支持中文字体,需要下载远东字体包iTextAsian.jar,否则不能往PDF文档中输出中文字体。通过下面的代码就可以在文档中使用中文了:
BaseFont.createFont(basePath + "/Font/SIMHEI.TTF", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
其中basePath 为你的项目工程路径,"/Font/SIMHEI.TTF"是把windows/Font目录下的字体复制到你项目工程下Font文件夹中。
向已有的PDF文件里新加一页
document.newPage();