使用itext-2.1.7生成word文档总结

来源:互联网 发布:用xcode编写c语言教程 编辑:程序博客网 时间:2024/05/21 18:27

一、综述

本人在项目中遇到了导出word文档这一功能,于是进行了一定的预研工作。因为以前使用过poi进行excel导出,所以开始的时候,我也是打算用poi实现这一功能的。但是在使用poi的过程中,发现编写的代码结构与html相比异常复杂和繁琐,再加上本人英文苦手,让我对这API一路找功能,简直难上加难。于是查阅了很多资料,终于找到了一种我认为比较简单的方式。就是使用itext-2.1.7,需要注意的是只有2.1.7这个版本可以实现这一功能,后续版本已经将该功能删除。下面总结一下简单的使用方法:

二、使用jar包:

itext-2.1.7.jar;
itext-rtf-2.1.7.jar;

三、开始使用

  1. 创建word文件
File f = new File("D:/buffer/");f.mkdirs();f = new File(f.getPath()+"/demo.doc");
  1. 创建itext文档对象
Document document = new Document(PageSize.A4);
  1. 创建RtfWriter对象
RtfWriter2.getInstance(document, new FileOutputStream(f));
  1. 插入段落
Paragraph p = new Paragraph("基本信息表", new Font(Font.NORMAL, 18, Font.BOLD, new Color(0, 0, 0)));document.add(p);
  1. 插入表格
    itext的表格没有行的概念,插入的都是单元格,itext内部会根据表格的列数自动进行换行。
Table table = new Table(2);//设置表格样式table.setBorderWidth(2f);table.setBorderColor(Color.BLACK);table.setPadding(5);table.setSpacing(0);table.setAlignment(1);//创建默认单元格Cell c = new Cell();c.setHorizontalAlignment(Cell.ALIGN_CENTER);c.setVerticalAlignment(Cell.ALIGN_MIDDLE);table.setDefaultCell(c);//创建单元格         Cell cell = new Cell(new Paragraph("名称","demo"));cell.setColspan(2);table.addCell(cell);document.add(table);
  1. 插入图片
Image img = Image.getInstance("D:/img.png");//调整图片宽高,并且锁定宽高比float width = 500;float height = img.getHeight()/img.getWidth()*width;img.scaleAbsolute(width,height);cell.add(img);
  1. 将html代码转换为文档内容
    实现html转换word的最简单的方法是,直接将html文件的后缀改成.doc即可,但是这种方式的实现是基于word可以解析html文件。也就是说,文件的格式并没有转换,只是通过word打开了而已。如果整个html页面都需要转换成word,那这种方法肯定是最高效的。但是这种情况往往较少,经常出现的是,文档的一部分内容是需要html转换的。针对这种情况,我查阅的大量的资料,终于找到了解决方案,如下:
public static void addHtmlContent(Object element, String html, String root, float imgWidth) throws IOException, DocumentException{    StyleSheet ss = new StyleSheet();    html = html.replace("..", root);    List<?> htmlList = HTMLWorker.parseToList(new StringReader(html), ss);      for (int i = 0 ; i < htmlList.size(); i++){        Element e = (Element) htmlList.get(i);        for (Object object : e.getChunks()) {            if(object instanceof Chunk){                Chunk ch = (Chunk) object;                if(ch.getImage() != null){                    float width = imgWidth;                    float height = ch.getImage().getHeight()/ch.getImage().getWidth()*width;                    ch.getImage().scaleAbsolute(width,height);                }            }        }        if(element instanceof Cell){            ((Cell)element).add(e);        }        if(element instanceof Paragraph){            ((Paragraph)element).add(e);        }        if(element instanceof Document){            ((Document)element).add(e);        }    }}

四、代码示例

package com.sv.demo.itext;import java.awt.Color;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.StringReader;import java.net.MalformedURLException;import java.util.List;import com.lowagie.text.Cell;import com.lowagie.text.Chunk;import com.lowagie.text.Document;import com.lowagie.text.DocumentException;import com.lowagie.text.Element;import com.lowagie.text.Font;import com.lowagie.text.Image;import com.lowagie.text.PageSize;import com.lowagie.text.Paragraph;import com.lowagie.text.Table;import com.lowagie.text.html.simpleparser.HTMLWorker;import com.lowagie.text.html.simpleparser.StyleSheet;import com.lowagie.text.rtf.RtfWriter2;public class ITextMain {    public static void main(String[] args) {        //创建文件        File f = new File("D:/buffer/");        f.mkdirs();        f = new File(f.getPath()+"/demo.doc");        //创建itext文档对象        Document document = new Document(PageSize.A4);        try {            //创建RtfWriter对象            RtfWriter2.getInstance(document, new FileOutputStream(f));            document.open();            Paragraph p = new Paragraph("基本信息表", new Font(Font.NORMAL, 18, Font.BOLD, new Color(0, 0, 0)));            p.setAlignment(1);            document.add(p);            //标题字体风格            Font tf = new Font();            tf.setStyle(Font.BOLD);            Table table = new Table(4);            table.setBorderWidth(2f);            table.setBorderColor(Color.BLACK);            table.setPadding(5);            table.setSpacing(0);            table.setAlignment(1);            Cell c = new Cell();            c.setHorizontalAlignment(Cell.ALIGN_CENTER);            c.setVerticalAlignment(Cell.ALIGN_MIDDLE);            table.setDefaultCell(c);            Cell cell = new Cell(new Paragraph("名称",tf));            table.addCell(cell);            cell = new Cell("测试");            table.addCell(cell);            cell = new Cell(new Paragraph("编号",tf));            table.addCell(cell);            cell = new Cell("demo001");            table.addCell(cell);            cell = new Cell("内容");            cell.setColspan(2);            table.addCell(cell);            cell = new Cell("测试内容测试内容测试内容测试内容测试内容测试内容测试内容测试内容测试内容测试内容");            cell.setColspan(2);            table.addCell(cell);            document.add(table);            //添加图片            try {                Image img = Image.getInstance("D:/Desert.jpg");                float width = 500;                float height = img.getHeight()/img.getWidth()*width;                img.scaleAbsolute(width,height);                document.add(img);            } catch (MalformedURLException e) {                System.err.println(e.getMessage());            } catch (IOException e) {                System.err.println(e.getMessage());            }            //添加html代码            String html = "<h1>htmlcontent</h1>"            + "<table border=\"1\" cellspacing=\"0\" cellpadding=\"0\">"                + "<thead>"                    + "<tr>"                        + "<th>第一列</th>"                        + "<th>第二列</th>"                    + "</tr>"                + "</thead>"                + "<tbody>"                    + "<tr>"                        + "<td>cell11</td>"                        + "<td>cell21</td>"                    + "</tr>"                + "</tbody>"            + "</table>";            ITextMain.addHtmlContent(document, html, "D:/", 500);        } catch (Exception e) {            System.err.println(e.getMessage());        } finally {            if(document != null){                document.close();            }        }    }    public static void addHtmlContent(Object element, String html, String root, float imgWidth) throws IOException, DocumentException{        StyleSheet ss = new StyleSheet();        html = html.replace("..", root);        List<?> htmlList = HTMLWorker.parseToList(new StringReader(html), ss);          for (int i = 0 ; i < htmlList.size(); i++){            Element e = (Element) htmlList.get(i);            for (Object object : e.getChunks()) {                if(object instanceof Chunk){                    Chunk ch = (Chunk) object;                    if(ch.getImage() != null){                        float width = imgWidth;                        float height = ch.getImage().getHeight()/ch.getImage().getWidth()*width;                        ch.getImage().scaleAbsolute(width,height);                    }                }            }            if(element instanceof Cell){                ((Cell)element).add(e);            }            if(element instanceof Paragraph){                ((Paragraph)element).add(e);            }            if(element instanceof Document){                ((Document)element).add(e);            }        }    }}
0 0
原创粉丝点击