利用IText生成Html文档
生成Html文档的步骤:
(1)建立Document对象实例
Document document = new Document();
(2)建立书写器(Writer)对象,并且与Document对象关联,书写器可以将具体文档存盘成对应的格式,out为输出流(OutputStream)。
HtmlWriter.getInstance(document,out)
(3)打开文档
document.open();
(4)输入内容,内容元素可有Chunk,Paragraph、Table、Graphic对象等构造,详细构造方法可看源码。
document.add(new Chunk(“Hello”));
(5)关闭文档
documen.close();
书写器(Writer)对象
一旦文档(Document)对象建立好之后,需要建立一个或者多个书写器(Writer)对象与之关联。通过书写器(Writer)对象可以将具体的文档存盘成所需要的格式,例如PDF.PDFWriter可以将文档存盘成PDF文件,html.HtmlWriter可以将文档存盘成Html文件。
添加文档内容
所有向文档添加的内容都是以对象为单位的,如Phrase、Paragraph、Table、Graphic对象等。比较常用的是段落(Paragraph)对象,用于向文档中添加一段文字。
设置文档摘要
(1) 设置文档的标题
public boolean addTitle(String title)
(2) 设置文档的主题、、创建程序
public boolean addSubject(String subject)
(3) 设置文档的关键字
public boolean addKeywords(String keywords)
(4) 设置文档的作者
public boolean addAuthor(String author)
(5) 设置文档的创建者
public boolean addCreator(String creator)
(6) 设置文档的生产者
public boolean addProducer()
(7) 设置文档的创建日期
public boolean addCreationDate()
(8) 设置文档的头信息
public boolean addHeader(String name, String content)
要注意的是设置文档属性要在文档打开前,且文档与读写器关联之后进行,否则报错。
OutputStream out = new FileOutputStream(file);
Document document = new Document(PageSize.A4);
HtmlWriter.getInstance(document, out);//设置文档属性应在书写器对象与文档对象关联之后。
document.addTitle("Hello World!");
document.addAuthor("mengkai");
document.addCreationDate();
document.addKeywords("keyword-mk");
document.open();//设置文档属性应在open()之前。
通过设置html属性,生成的html源文件可以看到
<html>
<head>
<title>
Hello World!
</title>
<meta name="author" content="mengkai" />
<!-- Creationdate: 星期四 十二月 24 14:47:28 CST 2015 -->
<meta name="keywords" content="keyword-mk" />
<!-- iText 2.0.6 (by lowagie.com) -->
<!-- CreationDate: Thu Dec 24 14:47:28 CST 2015 -->
</head>
<body leftmargin="36.0" rightmargin="36.0" topmargin="36.0" bottommargin="36.0">
<div>hello
</div>
</body>
</html>