IText一个入门例子

一、什么是iText

  iText是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。

  二、iText的下载安装

在http://www.lowagie.com/iText/download.html - download 网站上下载iText.jar文件后,只需要在系统的CLASSPATH中加入iText.jar的路径,在程序中就可以使用iText类库了。

  三、建立第一个PDF文档

  用iText生成PDF文档需要5个步骤:

  ①建立com.lowagie.text.Document对象的实例。
Document document = new Document();


②建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。


PDFWriter.getInstance(document, new FileOutputStream("Helloworld.PDF"));

  ③打开文档。


document.open();

  ④向文档中添加内容。


document.add(new Paragraph("Hello World"));

  ⑤关闭文档。


document.close();

完整代码如下:

import java.io.FileOutputStream;
import java.io.IOException;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

/**
* Generates a simple 'Hello World' PDF file.
*
* @author blowagie
*/

public class HelloWorld {

/**
* Generates a PDF file with the text 'Hello World'
*
* @param args no arguments needed here
*/
public static void main(String[] args) {

System.out.println("Hello World");

// step 1: creation of a document-object
Document document = new Document();
try {
// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a file
PdfWriter.getInstance(document,
new FileOutputStream("HelloWorld.pdf"));

// step 3: we open the document
document.open();
// step 4: we add a paragraph to the document
document.add(new Paragraph("Hello World"));
} catch (DocumentException de) {
System.err.println(de.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}

// step 5: we close the document
document.close();
}
}

  通过上面的5个步骤,就能产生一个Helloworld.PDF的文件,文件内容为"Hello World"。

当然,这只是个iText入门。其实iText官方网站上有很详细的示例。有兴趣可以去看看。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值