Java + Aspose Word TOC 工具完整构建流程

一、准备环境

1️⃣ 安装 JDK

bash 复制代码
java -version

2️⃣ 安装 Maven

bash 复制代码
mvn -version

确认可用

二、创建 Maven 项目(命令行方式)

1️⃣ 创建项目结构

bash 复制代码
mvn archetype:generate ^
-DgroupId=com.example ^
-DartifactId=word-toc-tool ^
-DarchetypeArtifactId=maven-archetype-quickstart ^
-DinteractiveMode=false

2️⃣ 进入项目

bash 复制代码
cd word-toc-tool

三、项目结构说明

生成后结构:

bash 复制代码
word-toc-tool/
│
├── pom.xml
└── src/
    ├── main/
    │   └── java/
    │       └── com/example/
    │           └── App.java
    └── test/

四、修改 Java 代码(关键补充)


1️⃣ 删除默认 App.java

bash 复制代码
src/main/java/com/example/App.java

2️⃣ 新建文件:

bash 复制代码
WordTocUpdater.java

路径:

bash 复制代码
src/main/java/com/example/WordTocUpdater.java

3️⃣ 核心代码(可直接用)

java 复制代码
package com.example;

import com.aspose.words.*;

public class WordTocUpdater {

    // =========================
    // 主方法:处理 Word
    // =========================
    public static String updateToc(String inputPath) {

        System.out.println("==================================");
        System.out.println("[1] 输入文件: " + inputPath);

        String outputPath = inputPath.substring(0, inputPath.lastIndexOf("."))
                + "_toc.docx";

        System.out.println("[2] 输出文件: " + outputPath);

        try {
            // =========================
            // 【核心】跨系统自动配置字体路径(兼容所有Aspose版本)
            // =========================
            System.out.println("[3] 检测系统并配置字体路径...");
            configFontsPath();

            // =========================
            // 加载 Word 文档
            // =========================
            System.out.println("[4] 加载 Word 文档...");
            Document doc = new Document(inputPath);

            // =========================
            // 第一步:先插入页码(必须最先执行)
            // =========================
            System.out.println("[5] 插入居中页码(当前页/总页数)...");
            insertPageNumber(doc);

            // =========================
            // 第二步:计算页面布局(固定分页)
            // =========================
            System.out.println("[6] 计算文档分页...");
            doc.updatePageLayout();

            // =========================
            // 第三步:更新所有字段(页码、目录依赖项)
            // =========================
            System.out.println("[7] 更新文档所有字段...");
            doc.updateFields();

            // =========================
            // 第四步:最后更新目录(此时页码已固定,100%准确)
            // =========================
            System.out.println("[8] 刷新目录页码...");
            refreshToc(doc);

            // =========================
            // 第五步:最终锁定布局
            // =========================
            System.out.println("[9] 最终确认分页...");
            doc.updatePageLayout();

            // =========================
            // 保存文件
            // =========================
            System.out.println("[10] 保存文件...");
            doc.save(outputPath, SaveFormat.DOCX);

            System.out.println("==================================");
            System.out.println("✅ 处理完成!文件路径: " + outputPath);

        } catch (Exception e) {
            System.out.println("❌ 处理失败");
            e.printStackTrace();
        }

        return outputPath;
    }

    /**
     * 【跨系统核心】自动识别 Windows / Linux 配置字体路径
     * 兼容所有低版本 Aspose.Words,无任何编译错误
     */
    private static void configFontsPath() {
        String os = System.getProperty("os.name").toLowerCase();
        try {
            if (os.contains("win")) {
                // Windows 系统字体路径
                String winFontPath = "C:/Windows/Fonts";
                FontSettings.getDefaultInstance().setFontsFolder(winFontPath, true);
                System.out.println("✅ 当前系统:Windows,字体路径:" + winFontPath);
            } else if (os.contains("linux")) {
                // Linux(Ubuntu) 自定义字体路径
                String linuxFontPath = "/usr/share/fonts/chinese";
                FontSettings.getDefaultInstance().setFontsFolder(linuxFontPath, true);
                System.out.println("✅ 当前系统:Linux,字体路径:" + linuxFontPath);
            }
        } catch (Exception e) {
            // 容错:不做额外操作,使用Aspose默认字体查找
            System.out.println("⚠️ 字体路径配置跳过,使用默认模式");
        }
    }

    /**
     * 插入页码:居中  当前页 / 总页数
     */
    private static void insertPageNumber(Document doc) throws Exception {
        for (Section section : doc.getSections()) {
            HeaderFooter footer = section.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY);
            if (footer == null) {
                footer = new HeaderFooter(doc, HeaderFooterType.FOOTER_PRIMARY);
                section.getHeadersFooters().add(footer);
            }
            // 清空原有页脚
            footer.removeAllChildren();

            // 创建居中段落
            Paragraph para = new Paragraph(doc);
            para.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);

            // 当前页码
            para.appendField(FieldType.FIELD_PAGE, true);
            para.appendChild(new Run(doc, " / "));
            // 总页数
            para.appendField(FieldType.FIELD_NUM_PAGES, true);

            footer.appendChild(para);
        }
    }

    /**
     * 仅刷新目录(TOC)字段
     */
    private static void refreshToc(Document doc) {
        for (Field field : doc.getRange().getFields()) {
            if (field.getType() == FieldType.FIELD_TOC) {
                try {
                    field.update();
                } catch (Exception e) {
                    System.out.println("⚠️ 单个目录更新失败: " + e.getMessage());
                }
            }
        }
    }

    // =========================
    // main入口
    // =========================
    public static void main(String[] args) {
        System.out.println("==================================");
        System.out.println("Word 目录+页码自动更新工具(跨Windows/Linux)");
        System.out.println("==================================");

        if (args.length == 0) {
            System.out.println("❌ 用法: java -jar xxx.jar 文档路径.docx");
            return;
        }

        updateToc(args[0]);

        System.out.println("==================================");
        System.out.println("程序结束");
        System.out.println("==================================");
    }
}

五、替换 pom.xml

改成Aspose 版本 + 打包插件:

bash 复制代码
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example</groupId>
  <artifactId>word-toc-tool</artifactId>
  <version>1.0</version>
  <packaging>jar</packaging>

  <dependencies>

    <!-- ⭐ 正确方式:普通依赖(关键修改) -->
    <dependency>
      <groupId>com.aspose</groupId>
      <artifactId>aspose-words</artifactId>
      <version>21.11</version>
    </dependency>

  </dependencies>

  <build>
    <plugins>

      <!-- ⭐ Maven Shade:打 fat jar -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>3.5.0</version>

        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>

            <configuration>

              <!-- ⭐ 防止依赖丢失 -->
              <createDependencyReducedPom>false</createDependencyReducedPom>

              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <mainClass>com.example.WordTocUpdater</mainClass>
                </transformer>
              </transformers>

            </configuration>

          </execution>
        </executions>

      </plugin>

    </plugins>
  </build>

</project>

六、安装 Aspose 到本地仓库

bash 复制代码
mvn install:install-file ^
-Dfile=aspose-words-24.7-jdk17.jar ^
-DgroupId=com.aspose ^
-DartifactId=aspose-words ^
-Dversion=24.7 ^
-Dpackaging=jar

七、打包

bash 复制代码
mvn clean package
相关推荐
琪伦的工具库1 天前
批量SRT转Word工具使用说明:支持SRT/ASS/SSA/VTT批量转DOCX或TXT,时间轴格式/合并多行/保留序号可选
word
一叶龙洲2 天前
Java中使用模板引擎(FreeMarker / Velocity) + Word XML导出复杂Word
xml·java·word
伟贤AI之路3 天前
为什么AI里的公式复制到Word格式会乱?
人工智能·word·latex
琪伦的工具库3 天前
批量DOCXPDFPPTX文档页拆分工具使用说明:每页拆分/每N页拆分/指定页码范围,支持导出日志
word
weixin_416660074 天前
从标记语言到 Word 文档:AI 生成的 Mermaid 与 LaTeX 自动化转换的技术方案解析
word·latex·数学公式·deepseek
昵称暂无15 天前
通过 C# 复制 Word 文档、指定段落、指定节
开发语言·c#·word
STRUGGLE_xlf6 天前
AI大模型生成表格粘贴到 Word 后出现双线边框的原因与解决方案
word
weixin_416660076 天前
2026 年 AI 对话转 Word 工具分析:Pandoc、Typora、aitoword 怎么选
人工智能·word
F_D_Z7 天前
Word Embedding :从分布式假设到神经网络语言模型
分布式·word·embedding