首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >《历史代码分析》3、生成简单的Word文档

《历史代码分析》3、生成简单的Word文档

作者头像
小码农薛尧
发布2025-03-07 16:28:43
发布2025-03-07 16:28:43
3580
举报
文章被收录于专栏:小码农薛尧小码农薛尧
本系列《历史代码分析》为工作中遇到具有代表性的代码。今天我们讲一下生成简单的Word文档,使用开源的itext库,2022年,此库的作者Bruno Lowagie已将iText Group公司股份全部卖给了PDFTron,所以本示例中的方法,无法保证在新版本中存在。

在pom.xml中引入库

代码语言:javascript
复制
       <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>

代码如下:

代码语言:javascript
复制
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文档,包含了标题、正文、图片、表格等内容,代码如下:

代码语言:javascript
复制
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();
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2025-03-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 小码农薛尧 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档