利用IText导出Word

本文介绍如何使用IText Java库生成Word文档,包括设置字体、插入标题、内容及图片等,并提供了示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    生成Word文档的类库有很多,如果格式固定可以使用freemaker ,但如果是需要手工生成的则常用的有jacob,poi,itext等等,jacob操作office的能力是不错的,但是对于我个人来说,我不喜欢它的两方面:一、jacob只能应用于windows平台。二、除了要把相应的ar包加载到类路径下,还需要把jacob.dll复制到windows/system32目录中。poi操作excel方面的能力非常强大,对于word方面的操作能力还是不够的。

       现在来说说IText吧。IText是用于生成PDF文档的一个Java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。当然也可以生成word文档。而且操作方法简单。使用IText需要3个jar包:iText-2.1.7.jar(核心包),iTextAsian.jar(解决中文输出问题),itext-rtf-2.1.7.jar(操作rtf格式)。(最后会提供jar包与实例下载)。

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

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

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

          RtfWriter2.getInstance(this.document, new FileOutputStream(filePath));

  ③打开文档。

          document.open();

  ④向文档中添加内容。

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

  ⑤关闭文档。(在最后必须关闭文档,否则即使生成了word文档也会打不开)

          document.close(); 

      下面提供一个通用文件给大家:

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. public class WordUtils {  
  2.     private Document document;  
  3.     private BaseFont bfChinese;  
  4.   
  5.     public BaseFont getBfChinese() {  
  6.         return bfChinese;    
  7.     }    
  8.     
  9.     public void setBfChinese(BaseFont bfChinese) {    
  10.         this.bfChinese = bfChinese;    
  11.     }    
  12.     
  13.     public Document getDocument() {    
  14.         return document;    
  15.     }    
  16.     
  17.     public void setDocument(Document document) {    
  18.         this.document = document;    
  19.     }    
  20.     
  21.     public WordUtils(){    
  22.         this.document = new Document(PageSize.A4);//设置纸张大小  
  23.             
  24.     }    
  25.     /** 建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中 
  26.      * @param filePath  要操作的文档路径,若文档不存在会自动创建 
  27.      * @throws com.lowagie.text.DocumentException 
  28.      * @throws java.io.IOException 
  29.      */    
  30.     public void openDocument(String filePath) throws DocumentException,    
  31.     IOException {    
  32. //       建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中    
  33.         RtfWriter2.getInstance(this.document, new FileOutputStream(filePath));    
  34.         this.document.open();    
  35. //       设置中文字体    
  36.         this.bfChinese = BaseFont.createFont("STSongStd-Light",    
  37.                 "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);  
  38.     }  
  39.         
  40.     /**  
  41.      * @param titleStr 标题 
  42.      * @param fontsize 字体大小  
  43.      * @param fontStyle 字体样式  
  44.      * @param elementAlign 对齐方式  
  45.      * @throws com.lowagie.text.DocumentException 
  46.      */    
  47.     public void insertTitle(String titleStr,int fontsize,int fontStyle,int elementAlign) throws DocumentException{    
  48.         Font titleFont = new Font(this.bfChinese, fontsize, fontStyle);    
  49.         Paragraph title = new Paragraph(titleStr);    
  50.         // 设置标题格式对齐方式    
  51.         title.setAlignment(elementAlign);    
  52.         title.setFont(titleFont);    
  53.             
  54.         this.document.add(title);    
  55.     }    
  56.         
  57.   
  58.   
  59.     /** 
  60.      * 设置带有目录格式的标题(标题1格式) 
  61.      * 
  62.      * @param rtfParagraphStyle 标题1样式 
  63.      * @param titleStr 标题 
  64.      * @throws DocumentException 
  65.      */  
  66.     public void insertTitlePattern(String titleStr, RtfParagraphStyle rtfParagraphStyle) throws DocumentException{  
  67.         Paragraph title = new Paragraph(titleStr);  
  68.         title.setFont(rtfParagraphStyle);  
  69.         this.document.add(title);  
  70.     }    
  71.       
  72.   
  73.     /** 
  74.      * 设置带有目录格式的标题(标题2格式) 
  75.      * @param titleStr 标题 
  76.      * @param rtfParagraphStyle 标题2样式 
  77.      * @throws DocumentException 
  78.      */  
  79.     public void insertTitlePatternSecond(String titleStr,RtfParagraphStyle rtfParagraphStyle) throws DocumentException{  
  80.         Paragraph title = new Paragraph(titleStr);  
  81.         // 设置标题格式对齐方式    
  82.         title.setFont(rtfParagraphStyle);  
  83.         this.document.add(title);  
  84.     }    
  85.       
  86.       
  87.     /**  
  88.      * @param tableName 标题  
  89.      * @param fontsize 字体大小  
  90.      * @param fontStyle 字体样式  
  91.      * @param elementAlign 对齐方式  
  92.      * @throws com.lowagie.text.DocumentException 
  93.      */    
  94.     public void insertTableName(String tableName,int fontsize,int fontStyle,int elementAlign) throws DocumentException{    
  95.         Font titleFont = new Font(this.bfChinese, fontsize, fontStyle);    
  96.         titleFont.setColor(102102153);  
  97.         Paragraph title = new Paragraph(tableName);    
  98.         // 设置标题格式对齐方式    
  99.         title.setAlignment(elementAlign);    
  100.         title.setFont(titleFont);    
  101.             
  102.         this.document.add(title);    
  103.     }    
  104.       
  105.     /**  
  106.      * @param contextStr 内容  
  107.      * @param fontsize 字体大小  
  108.      * @param fontStyle 字体样式  
  109.      * @param elementAlign 对齐方式  
  110.      * @throws com.lowagie.text.DocumentException 
  111.      */    
  112.     public void insertContext(String contextStr,int fontsize,int fontStyle,int elementAlign) throws DocumentException{    
  113.         // 正文字体风格    
  114.         Font contextFont = new Font(bfChinese, fontsize, fontStyle);    
  115.         Paragraph context = new Paragraph(contextStr);    
  116.         //设置行距    
  117.         context.setLeading(3f);  
  118.         // 正文格式左对齐    
  119.       //  context.setAlignment(elementAlign);  
  120.         context.setFont(contextFont);    
  121.         // 离上一段落(标题)空的行数    
  122.         context.setSpacingBefore(1);  
  123.         // 设置第一行空的列数    
  124.         context.setFirstLineIndent(20);    
  125.         document.add(context);    
  126.     }  
  127.   
  128.   
  129.     /** 
  130.      * @param imgUrl 图片路径 
  131.      * @param imageAlign 显示位置 
  132.      * @param height 显示高度 
  133.      * @param weight 显示宽度 
  134.      * @param percent 显示比例 
  135.      * @param heightPercent 显示高度比例 
  136.      * @param weightPercent 显示宽度比例 
  137.      * @param rotation 显示图片旋转角度 
  138.      * @throws java.net.MalformedURLException 
  139.      * @throws java.io.IOException 
  140.      * @throws com.lowagie.text.DocumentException 
  141.      */  
  142.     public void insertImg(String imgUrl,int imageAlign,int height,int weight,int percent,int heightPercent,int weightPercent,int rotation) throws MalformedURLException, IOException, DocumentException{    
  143. //       添加图片    
  144.         Image img = Image.getInstance(imgUrl);    
  145.         if(img==null)    
  146.             return;    
  147.         img.setAbsolutePosition(00);    
  148.         img.setAlignment(imageAlign);    
  149.         img.scaleAbsolute(height, weight);  
  150.         img.scaleAbsolute(10001000);  
  151.         img.scalePercent(percent);  
  152.         img.scalePercent(heightPercent, weightPercent);    
  153.         img.setRotation(rotation);    
  154.         document.add(img);  
  155.     }  
  156.   
  157.     /** 
  158.      * 添加简单表格 
  159.      * @param column 表格列数(必须) 
  160.      * @param row 表格行数 
  161.      * @throws DocumentException 
  162.      */  
  163.     public void insertSimpleTable(int column,int row) throws DocumentException {  
  164.         Table table=new Table(column);//列数必须设置,而行数则可以按照个人要求来决定是否需要设置  
  165.         table.setAlignment(Element.ALIGN_CENTER);// 居中显示  
  166.         table.setAlignment(Element.ALIGN_MIDDLE);// 纵向居中显示  
  167.         table.setAutoFillEmptyCells(true);// 自动填满  
  168.         table.setBorderColor(new Color(0125255));// 边框颜色  
  169.         table.setBorderWidth(1);// 边框宽度  
  170.         table.setSpacing(2);// 衬距,  
  171.         table.setPadding(2);// 即单元格之间的间距  
  172.         table.setBorder(20);// 边框  
  173.         for (int i = 0; i < column*3; i++) {  
  174.             table.addCell(new Cell(""+i));  
  175.         }  
  176.         document.add(table);  
  177.     }  
  178.     /** 
  179.      * 在操作完成后必须关闭document,否则即使生成了word文档,打开也会发生错误 
  180.      * @throws DocumentException 
  181.      */  
  182.     public void closeDocument() throws DocumentException{    
  183.         this.document.close();    
  184.     }    
  185.       
  186. }  

当然,上面还有一些表格的方法没有写出来,因为每个人的需求都是不同的,本人写了一个小例子,显示效果为:

显示效果

表格显示效果


   下面提供IText的jar包:   IText jar包(免积分)

   这是上面显示IText操作效果的demo源代码: Demo(免积分)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值