java 实现读取word文档的目录结构以及对应的跳转页数

我有一个法务系统,需要实现word在线预览,此时我需要提前word文档的目录大纲,以及实现跳转对应页数(因为产品不允许下载文档在本地打开,文件隐私问题)
案例如下

img

https://blog.csdn.net/knqi007/article/details/73899854
看看这个poi这个工具可以

可以参考如下Java代码来读取Word中的目录以及对应的页数:

import com.spire.doc.Document;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class GetTOC {
    public static void main(String[] args) throws IOException {
        //加载包含目录的Word文档
        Document doc = new Document();
        doc.loadFromFile("目录2.docx");

        //获取第一节
        Section section = doc.getSections().get(0);

        //保存目录内容到.txt文档
        File file = new File("GetToc.txt");
        if (file.exists())
        {
            file.delete();
        }
        file.createNewFile();
        FileWriter fw = new FileWriter(file, true);
        BufferedWriter bw = new BufferedWriter(fw);

        //遍历第一节中的所有段落
        for (int i = 0; i < section.getParagraphs().getCount(); i++)
        {
            Paragraph paragraph = section.getParagraphs().get(i);
            //判断是否为目录域
            if (paragraph.getStyleName().matches("TOC\\w+"))
            {
                //获取目录中的文本内容
                String text = paragraph.getText();
                //写入txt文档
                bw.write( text+"\r");
            }
            bw.write("\n");
        }

        bw.flush();
        bw.close();
        fw.close();
    }
}

读取效果:

img


程序里面引入free spire.doc for Java包中的jar就可以实现读取了。