ITEXT 生成一个PDF
如何使用ITEXT来生成PDF文件呢?来看一个最简单的例子
package chapter1;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
import java.io.IOException;
public class SimplePdfDocument {
public static final String FILENAME= "helloworld.pdf";
public void createPdf(String filename) throws DocumentException, IOException {
// 第一步 创建PDF的文档对象
Document document = new Document();
// 第二步 使用PDF的文档对象创建PDF文件
PdfWriter.getInstance(document, new FileOutputStream(filename));
// 第三步 打开PDF文档对象
document.open();
// 第四步 向PDF文档中添加内容
document.add(new Paragraph("Hello World!"));
// 第五步 关闭PDF文档对象
document.close();
}
public static void main(String[] args) throws IOException, DocumentException {
new SimplePdfDocument().createPdf(FILENAME);
}
}
接下来,通过document类的一些方法,来了解Document的使用
Itext的Document类共有3个构造器
默认构造器,默认时用的是A4的纸张大小,这种纸张大小也是我们最常使用的纸张类型,PageSize中封装了多种纸张类型,基本涵盖我们日常使用的需求,如有特殊要求不在PageSize中,可以自定义一个 Rectangle rectangle = new Rectangle(100f,200f) 实例,指定长、宽长度即可。
构造器二传入一个RectAngle(矩形),用于设置文档纸张,可用PageSize中的静态Rectangle实例,也可自定义Rectangle实例,默认文档边距左右上下均为36
构造器三传入一个Rectangle和文档页面边距长度设置,顺序是左、右、上、下
/**
* Constructs a new <CODE>Document</CODE> -object.
*/
public Document() {
this(PageSize.A4);
}
/**
* Constructs a new <CODE>Document</CODE> -object.
*
* @param pageSize the pageSize
*/
public Document(Rectangle pageSize) {
this(pageSize, 36, 36, 36, 36);
}
/**
* Constructs a new <CODE>Document</CODE> -object.
*
* @param pageSize the pageSize
* @param marginLeft the margin on the left
* @param marginRight the margin on the right
* @param marginTop the margin on the top
* @param marginBottom the margin on the bottom
*/
public Document(Rectangle pageSize, float marginLeft, float marginRight,float marginTop, float marginBottom) {
this.pageSize = pageSize;
this.marginLeft = marginLeft;
this.marginRight = marginRight;
this.marginTop = marginTop;
this.marginBottom = marginBottom;
}
设置文档属性
// 设置作者
document.addAuthor("china is good.");
// 设置标题
document.addTitle("360 5 个日出");
// 设置主题
document.addSubject("360");
// 设置关键字
document.addKeywords("pdf,360");
// 创建人信息
document.addCreator("罗纳尔多");
// 设置文档纸张类型
document.setPageSize(PageSize.A4);
// 设置文档页边距(左、右、上、下)
document.setMargins(45, 45, 55, 40);