欢迎使用CSDN-markdown编辑器

来源:互联网 发布:程序员常用app 编辑:程序博客网 时间:2024/05/21 10:59

最近因为项目需要,利用了iText生成word。在网上查找了很多资料,也翻阅了很多之前大牛写的博客。特此在这里整理一下项目中使用的技术点。
jar使用的是iTextAsian.jar , iText-4.2.jar,itext-rtf-4.2.jar
①建立Document对象的实例。
  Document document = new Document();
②建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
  RtfWriter.getInstance(document, new FileOutputStream(“D:\Helloworld.doc”));
③打开文档。
  document.open();
④向文档中添加内容。
  document.add(new Paragraph(“Hello World”));
⑤关闭文档。
  document.close();
  通过上面的5个步骤,就能产生一个Helloworld.doc的文件,文件内容为”Hello World”。

1,生成一个word文档!

public class iTextDemp{    public static void main(String[]args){    /*这一行代码的意识是,我创建一个document的势力,将页面大小设置为A4,后面的数字是设置左右上下边距*/        Document document = new Document(PageSize.A4,72,60,72,60);        /*建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中*/        RtfWriter.getInstance(document, new FileOutputStream(“D:\Helloworld.doc”));        //接下来是打开document        document.open();        Paragraph p = new Paragraph("插入daodocument中!!!");        document.add(p);        //关闭document        document.close();    }}

以上完成了一个简单的document的创建。下面是介绍一些document中常见的应用方法。
首先是要将word中得某几张设置成横向或者是纵向。这也是我在做这个项目中最耗时间的地方。之前在网上找了很多大牛写的博客,发现并没有。然后我在自己看API试用的情况下,得出了结论。首先你得先设置章节,比如设置两章。一章是横向,一章是纵向。下面是代码。

2,设置指定页面的纸张方向。

public class iTextDemo1{    public static void main(String[]args){        Document document = new Document(PageSize.A4.rotate(),72,60,72,60);        RtfWriter.getInstance(document, new FileOutputStream(“D:\Helloworld.doc”));        document.open();        //这里是创建章节。我们在这里创建了两章        Chapter chapter1 = new Chapter(1);        Paragraph p1 = new Paragraph("这里是第一章节的内容!!!");        chapter1.add(p1);        document.add(chapter1);        Chapter chapter2 = new Chapter(2);        Paragraph p2 = new Paragraph("这里是第二章节的内容!!!");        //设置纵向的word        document.setPageSize(PageSize.A4);        document.setMargins(72,60,72,60);        chapter1.add(p2);        document.add(chapter2);        document.close();    }}

这篇就写到这里了。
http://rensanning.iteye.com/blog/1538689
这篇文博有更多的详细的方法!

0 0
原创粉丝点击