您的位置:首页 > 编程语言 > Java开发

Java导出pdf<1>

2011-08-26 18:47 573 查看
JavaWeb整合开发王者归来、这书还不错

package com.helloweenvsfei.itext;
import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
public class FirstPDF {

public static void main(String[] args) {
// 创建文档对象,A4纸大小
Document document = new Document(PageSize.A4);
try {
// 输出为E:\itext.pdf文件
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream("E:\\itext.pdf "));
// 打开文档
document.open();
// 在pdf文件中写入文字
document.add(new Paragraph("Hello World, Hello iText"));
// 关闭文档
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

该程序运行后,将在E盘的根目录下生成一个itext.pdf文件,该pdf文件打开后,效果如图40.2所示。
(点击查看大图)图40.2 iText生成的pdf文件

通过以上的程序,总结出使用iText生成一个pdf的步骤如下:

(1)创建Document对象。

Document document = new Document();

其中,Document有3个构造方法,如下:

public Document();

public Document(Rectangle pageSize);

public Document(Rectangle pageSize,int marginLeft,int marginRight,int marginTop,int marginBottom)。

pageSize是纸张类型的大小,通常可以使用PageSize中的常量来表示,例如PageSize.A4表示A4纸张。marginLeft、marginRight、marginTop和marginBottom分别是正文距离页边的左、右、上、下的补白大小。

(2)创建书写器(Writer)与document对象关联,通过书写器可以将文档写入磁盘中。
PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream
("E:\\itext.pdf "));

(3)打开文档。
document.open();

(4)写入文档内容。
document.add(new Paragraph("Hello iText"));

写入的文档内容可以是多种类型,这里是带格式的文本Paragraph,还可以是Phrase、Paragraph、Table、Graphic对象等。

(5)关闭文档。
document.close();

通过以上5个步骤,就可以生成pdf文档了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息