在pom.xml中引入库
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext-rtf</artifactId>
<version>2.1.7</version>
</dependency>
代码如下:
package tech.xueyao.util;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.*;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.rtf.RtfWriter2;
import com.lowagie.text.rtf.style.RtfParagraphStyle;
import lombok.Getter;
import lombok.Setter;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Map;
/**
* @author Simon.Xue
* @date 2019-12-04 21:47
**/
@Getter
@Setter
publicclass WordUtils {
privatestatic Document document;
private BaseFont bfChinese;
public WordUtils() {
//设置纸张大小
document = new Document(PageSize.A4);
}
/**
* 创建一个Writer与document对象关联
* @param fileName 文档路径,没有则创建
* @throws Exception
*/
public void openDocument(String fileName, HttpServletResponse response) throws Exception{
fileName = new String(fileName.getBytes(),"utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
response.setHeader("Content-Disposition", "attachment;filename = " + fileName);
OutputStream outputStream = response.getOutputStream();
RtfWriter2.getInstance(document,
outputStream);
document.open();
this.bfChinese = BaseFont.createFont("Times-Roman",
"winansi", BaseFont.NOT_EMBEDDED);
}
/**
* 创建一个Writer与document对象关联
* @param filePath 文档路径,没有则创建
* @throws Exception
*/
public void openDocument(String filePath) throws Exception{
RtfWriter2.getInstance(document,
new FileOutputStream(filePath));
document.open();
this.bfChinese = BaseFont.createFont("Times-Roman",
"winansi", BaseFont.NOT_EMBEDDED);
}
/**
* 添加标题
* @param titleStr 标题
* @param fontSize 字体大小
* @param fontStyle 字体样式
* @param elementAlign 对齐方式
* @throws Exception
*/
public void insertTitle(String titleStr, int fontSize,
int fontStyle, int elementAlign) throws Exception{
Font titleFont = new Font((this.bfChinese), fontSize, fontStyle);
Paragraph title = new Paragraph(titleStr);
//设置标题格式对齐方式
title.setAlignment(elementAlign);
title.setFont(titleFont);
document.add(title);
}
/**
* 设置带有目录格式的标题(标题1格式)
* @param titleStr
* @param rtfParagraphStyle
* @throws Exception
*/
public void insertTitlePattern(String titleStr,
RtfParagraphStyle rtfParagraphStyle) throws Exception{
Paragraph title = new Paragraph(titleStr);
title.setFont(rtfParagraphStyle);
document.add(title);
}
/**
* 设置带目录格式的标题(标题2格式)
* @param titleStr
* @param rtfParagraphStyl
* @throws DocumentException
*/
public void insertTitlePatternSecond(String titleStr,
RtfParagraphStyle rtfParagraphStyl) throws DocumentException {
Paragraph title = new Paragraph(titleStr);
//设置标题格式对齐方式
title.setFont(rtfParagraphStyl);
document.add(title);
}
/**
* 添加表名
* @param tableName
* @param fontSize
* @param fontStyle
* @param elementAlign
* @throws DocumentException
*/
public void insertTableName(String tableName, int fontSize,
int fontStyle, int elementAlign) throws DocumentException {
Font titleFont = new Font(this.bfChinese, fontSize, fontStyle);
titleFont.setColor(102, 102, 153);
Paragraph title = new Paragraph(tableName);
//设置标题格式对齐方式
title.setAlignment(elementAlign);
title.setFont(titleFont);
document.add(title);
}
/**
* 添加内容
* @param contextStr 内容部分
* @param fontSize 字体大小
* @param fontStyle 字体样式
* @param elementAlign 对齐方式
* @throws DocumentException
*/
public void insertContext(String contextStr, int fontSize,
int fontStyle, int elementAlign) throws DocumentException {
Font contentFont = new Font(bfChinese, fontSize, fontStyle);
Paragraph context = new Paragraph(contextStr);
//设置行距
//context.setLeading(3f);
context.setFont(contentFont);
document.add(context);
}
/**
* 添加内容
* @param contextStr 内容部分
* @throws DocumentException
*/
public void insertContextAgent(String contextStr) throws DocumentException {
Font contentFont = new Font(bfChinese, 15, 1);
Paragraph context = new Paragraph(contextStr);
context.setFont(contentFont);
document.add(context);
}
/**
* 添加内容 快递地址
* @param contextStr 内容部分
* @throws DocumentException
*/
public void insertContextAddress(String contextStr) throws DocumentException {
Font contentFont = new Font(bfChinese, 9, 0);
Paragraph context = new Paragraph(contextStr);
context.setFont(contentFont);
document.add(context);
}
/**
* 添加内容 备注
* @param contextStr
* @throws DocumentException
*/
public void insertContextRemark(String contextStr) throws DocumentException {
Font contentFont = new Font(bfChinese, 10, 0);
contentFont.setColor(Color.RED);
Paragraph context = new Paragraph(contextStr);
context.setFont(contentFont);
document.add(context);
}
/**
* 插入一行空格
* @throws DocumentException
*/
public void insertContextLine() throws DocumentException {
Paragraph context = new Paragraph();
//设置行距
context.setLeading(3f);
//离上一段落(标题)空的行数
context.setSpacingAfter(2);
document.add(context);
}
/**
* 添加图片
* @param imgUrl 图片路径
* @param imageAlign 显示位置
* @param height 显示高度
* @param weight 显示宽度
* @param percent 显示比例
* @param heightPercent 显示高度比例
* @param weightPercent 显示宽度比例
* @param rotation 显示图片旋转角度
* @throws Exception
*/
public void insertImg(String imgUrl, int imageAlign, int height,
int weight, int percent, int heightPercent,
int weightPercent, int rotation) throws Exception {
Image img = Image.getInstance(imgUrl);
if (null == img) {
return;
}
img.setAbsolutePosition(0, 0);
img.setAlignment(imageAlign);
img.scaleAbsolute(height, weight);
img.scaleAbsolute(1000, 1000);
img.scalePercent(percent);
img.scalePercent(heightPercent, weightPercent);
img.setRotation(rotation);
document.add(img);
}
/**
* 添加简单表格
* @param column 表格列数(必须)
* @throws Exception
*/
public void insertSimpleTable(int column, Map<String, String> map) throws Exception {
int row = 2;
//设置列数
Table table = new Table(column, row);
//居中显示
table.setAlignment(Element.ALIGN_CENTER);
//纵向居中显示
table.setAlignment(Element.ALIGN_MIDDLE);
//自动填满
table.setAutoFillEmptyCells(true);
Cell cell;
column = 0;
for (String key : map.keySet()) {
row = 0;
cell = new Cell(key);
//水平居中
cell.setHorizontalAlignment(1);
table.addCell(cell, row, column);
cell = new Cell(map.get(key));
//水平居中
cell.setHorizontalAlignment(1);
row ++;
table.addCell(cell, row, column);
column ++;
}
document.add(table);
}
/**
* 关闭document
*/
public void closeDocument() {
document.close();
}
}
下面是用这个工具类创建一个Word文档,包含了标题、正文、图片、表格等内容,代码如下:
import tech.xueyao.util.WordUtils;
import com.lowagie.text.rtf.style.RtfParagraphStyle;
import java.util.HashMap;
import java.util.Map;
publicclass GenerateWordArticle {
public static void main(String[] args) {
try {
// 创建 WordUtils 实例
WordUtils wordUtils = new WordUtils();
// 打开文档,指定保存路径
wordUtils.openDocument("fruit_article.doc");
// 添加主标题
wordUtils.insertTitle("水果介绍", 20, 1, 1);
// 插入一行空格
wordUtils.insertContextLine();
// 添加段落标题
wordUtils.insertTitle("水果的重要性", 16, 1, 1);
// 添加正文内容
wordUtils.insertContext("水果是人们日常饮食中不可或缺的一部分。它们富含维生素、矿物质和膳食纤维,对身体健康非常有益。", 12, 0, 1);
// 插入图片
wordUtils.insertImg("example.jpg", 1, 200, 200, 50, 50, 50, 0);
// 插入一行空格
wordUtils.insertContextLine();
// 添加段落标题
wordUtils.insertTitle("常见水果介绍", 16, 1, 1);
// 创建表格数据
Map<String, String> fruitMap = new HashMap<>();
fruitMap.put("苹果", "富含维生素 C 和纤维素,有助于消化。");
fruitMap.put("香蕉", "含有丰富的钾元素,能维持心脏正常功能。");
fruitMap.put("橙子", "维生素 C 含量高,具有抗氧化作用。");
// 添加简单表格
wordUtils.insertSimpleTable(fruitMap.size(), fruitMap);
// 插入一行空格
wordUtils.insertContextLine();
// 添加备注内容
wordUtils.insertContextRemark("以上是一些常见水果的介绍,大家可以根据自己的口味和需求选择适合自己的水果。");
// 关闭文档
wordUtils.closeDocument();
System.out.println("Word 文档生成成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
}