POI实现word转html(带图片),实现word在线预览

一.添加maven依赖

主要使用了以下和poi相关的依赖,为了便于获取html的图片元素,还使用了jsoup:

一.添加maven依赖
主要使用了以下和poi相关的依赖,为了便于获取html的图片元素,还使用了jsoup:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.14</version>
</dependency>
 
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>3.14</version>
</dependency>
 
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.14</version>
</dependency>
 
<dependency>
    <groupId>fr.opensagres.xdocreport</groupId>
    <artifactId>xdocreport</artifactId>
    <version>1.0.6</version>
</dependency>
 
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>3.14</version>
</dependency>
 
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>ooxml-schemas</artifactId>
    <version>1.3</version>
</dependency>
 
<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.11.3</version>
</dependency>

二.word转换为html
在springboot项目的resources目录下新建static文件夹,将需要转换的word文件temp.docx粘贴进去,由于static是springboot的默认资源文件,所以不需要在配置文件里面另行配置了,如果改成其他名字,需要在application.yml进行相应配置。

doc格式转换为html:

public static String docToHtml() throws Exception {
    File path = new File(ResourceUtils.getURL("classpath:").getPath());
    String imagePathStr = path.getAbsolutePath() + "\\static\\image\\";
    String sourceFileName = path.getAbsolutePath() + "\\static\\test.doc";
    String targetFileName = path.getAbsolutePath() + "\\static\\test2.html";
    File file = new File(imagePathStr);
    if(!file.exists()) {
        file.mkdirs();
    }
    HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(sourceFileName));
    org.w3c.dom.Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(document);
    //保存图片,并返回图片的相对路径
    wordToHtmlConverter.setPicturesManager((content, pictureType, name, width, height) -> {
        try (FileOutputStream out = new FileOutputStream(imagePathStr + name)) {
            out.write(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "image/" + name;
    });
    wordToHtmlConverter.processDocument(wordDocument);
    org.w3c.dom.Document htmlDocument = wordToHtmlConverter.getDocument();
    DOMSource domSource = new DOMSource(htmlDocument);
    StreamResult streamResult = new StreamResult(new File(targetFileName));
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer serializer = tf.newTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty(OutputKeys.METHOD, "html");
    serializer.transform(domSource, streamResult);
    return targetFileName;
}

docx格式转换为html

public static String docxToHtml() throws Exception {
    File path = new File(ResourceUtils.getURL("classpath:").getPath());
    String imagePath = path.getAbsolutePath() + "\\static\\image";
    String sourceFileName = path.getAbsolutePath() + "\\static\\test.docx";
    String targetFileName = path.getAbsolutePath() + "\\static\\test.html";
 
    OutputStreamWriter outputStreamWriter = null;
    try {
        XWPFDocument document = new XWPFDocument(new FileInputStream(sourceFileName));
        XHTMLOptions options = XHTMLOptions.create();
        // 存放图片的文件夹
        options.setExtractor(new FileImageExtractor(new File(imagePath)));
        // html中图片的路径
        options.URIResolver(new BasicURIResolver("image"));
        outputStreamWriter = new OutputStreamWriter(new FileOutputStream(targetFileName), "utf-8");
        XHTMLConverter xhtmlConverter = (XHTMLConverter) XHTMLConverter.getInstance();
        xhtmlConverter.convert(document, outputStreamWriter, options);
    } finally {
        if (outputStreamWriter != null) {
            outputStreamWriter.close();
        }
    }
    return targetFileName;
}

转换成功后会生成对应的html文件,如果想在前端展示,直接读取文件转换为String返回给前端即可。

public static String readfile(String filePath) {
    File file = new File(filePath);
    InputStream input = null;
    try {
        input = new FileInputStream(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    StringBuffer buffer = new StringBuffer();
    byte[] bytes = new byte[1024];
    try {
        for (int n; (n = input.read(bytes)) != -1;) {
            buffer.append(new String(bytes, 0, n, "utf8"));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return buffer.toString();
}
(0)
上一篇 2024年 3月 4日 下午5:10
下一篇 2024年 3月 28日 上午8:47

相关文章

  • VIM1 Build Linux U-Boot

    We provided Fenix for you to build the Ubuntu OS images easily. You can follow the steps bellow to build U-Boot. Setup Environment Choose your board (e.g. VIM1), U-Boot version, Li…

    未分类 2023年 2月 12日
  • Amlogic S905X 开发板资料

    VIM1 创建可启动 TF 卡 [卡达斯文档] (khadas.com)

    未分类 2023年 2月 12日
  • OpenHarmony 3.0 虚拟机开发环境

    本文介绍一种简单的OpenHarmony环境搭建方法。 首先我们要知道环境搭建包括哪些内容,这样我们才好知道如何去搭建。通常来说,环境搭建包括这3大部分:代码编写、代码编译、代码下载、烧录程序。 在OpenHarmony中环境搭建主要分为两部分:(1)Windows环境——主要用于代码编写、烧录程序,这里华为给出了一套基于VS Code的解决方案。(2)Li…

    2023年 2月 9日
  • rc4继续探索

    未分类 2024年 4月 16日
  • 大兴调查研究之风 推动主题教育走深走实

    当前,学习贯彻习近平新时代中国特色社会主义思想主题教育正在全党开展。党中央决定,在全党大兴调查研究,作为在全党开展的主题教育的重要内容。调查研究是马克思主义世界观和方法论的集中体现,是党的思想路线和群众路线的内在要求,充分彰显了中国共产党人的鲜明政治品格和强大政治优势。以这次主题教育为契机,大兴调查研究之风,对于促进广大党员、干部全面学习领会习近平新时代中国…

    未分类 2023年 5月 13日
  • rc4

    未分类 2024年 4月 15日