首页 > 其他分享 >word转html

word转html

时间:2023-11-07 20:48:47浏览次数:22  
标签:word String import flag html poi new

目录

word转html

1. maven依赖

<!--word解析html -->
<!-- 针对2007以上版本的库docx -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>
<!-- 针对2003版本的库doc -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>fr.opensagres.xdocreport</groupId>
    <artifactId>fr.opensagres.poi.xwpf.converter.xhtml</artifactId>
    <version>2.0.2</version>
</dependency>

2. 实例

package com.baidu.cms.utils;
import cn.hutool.core.img.ImgUtil;
import fr.opensagres.poi.xwpf.converter.xhtml.Base64EmbedImgManager;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;


/**
 * word 转换成html
 */
public class WordUtils {
    private final static Logger log = LoggerFactory.getLogger(WordUtils.class);

    /**word转写html
     * @param sourcePath 源文件路径
     * @param outPath    解析后的文件路径
     * @return
     */
    public static boolean word2Html(String sourcePath, String outPath) {
        boolean flag = false;
        try {
            File file = new File(sourcePath);
            if (!file.exists()) {
                return flag;
            }
            String fName = file.getName();
            String suffix = fName.substring(fName.lastIndexOf(".") + 1).toLowerCase();
            if (suffix.endsWith("doc")) {
                flag = docToHtml(sourcePath, outPath);
            } else if (suffix.endsWith("docx")) {
                flag = docxToHtml(sourcePath, outPath);
            }
            // 新增标签-解决中文内容乱码
            boolean editFlag = editHtml(outPath);
            log.info("word2html({}->{}):parser({});edit({})", sourcePath, outPath, flag, editFlag);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("word2htmlError({}->{}):{}", sourcePath, outPath, String.valueOf(e));
        }
        return flag;
    }

    /**
     * 将word2003转换为html文件
     * @param wordPath word文件路径
     * @param htmlPath html文件路径
     */
    public static boolean docToHtml(String wordPath, String htmlPath) {
        boolean flag = false;
        try {
            File htmlFile = new File(htmlPath);
            // 原word文档
            InputStream input = new FileInputStream(new File(wordPath));
            HWPFDocument wordDocument = new HWPFDocument(input);
            WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
                    DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());

            wordToHtmlConverter.setPicturesManager((content, pictureType, suggestedName, widthInches, heightInches) -> {
                BufferedImage bufferedImage = ImgUtil.toImage(content);
                String base64Img = ImgUtil.toBase64(bufferedImage, pictureType.getExtension());
                //  带图片的word,则将图片转为base64编码,保存在一个页面中
                StringBuilder sb = (new StringBuilder(base64Img.length() + "data:;base64,".length()).append("data:;base64,").append(base64Img));
                return sb.toString();
            });

            // 解析word文档
            wordToHtmlConverter.processDocument(wordDocument);
            Document htmlDocument = wordToHtmlConverter.getDocument();
            // 生成html文件上级文件夹
            File folder = htmlFile.getParentFile();
            if (!folder.exists()) {
                folder.mkdirs();
            }

            // 生成html文件地址
            OutputStream outStream = new FileOutputStream(htmlFile);
            DOMSource domSource = new DOMSource(htmlDocument);
            StreamResult streamResult = new StreamResult(outStream);
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer serializer = factory.newTransformer();
            serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty(OutputKeys.METHOD, "html");
            serializer.transform(domSource, streamResult);
            outStream.close();
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Doc解析异常({}->{}):{}", wordPath, htmlPath, String.valueOf(e));
        }
        return flag;
    }

    /**
     * 2007版本word转换成html
     * @param wordPath word文件路径
     * @param htmlPath html文件路径
     * @return
     * @throws IOException
     */
    public static boolean docxToHtml(String wordPath, String htmlPath) {
        boolean flag = false;
        try {
            ZipSecureFile.setMinInflateRatio(-1.0d);
            File htmlFile = new File(htmlPath);
            File parentFile = htmlFile.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            // 图片保存路径
            String imagePath = parentFile.getPath() + "image" + File.separator;

            // word文件
            File wordFile = new File(wordPath);

            // 加载word文档生成 XWPFDocument对象
            InputStream in = new FileInputStream(wordFile);
            XWPFDocument document = new XWPFDocument(in);

            // 解析 XHTML配置 (这里设置IURIResolver来设置图片存放的目录)
            File imgFolder = new File(imagePath);
            //  带图片的word,则将图片转为base64编码,保存在一个页面中
            XHTMLOptions options = XHTMLOptions.create().indent(4).setImageManager(new Base64EmbedImgManager());
            // 将 XWPFDocument转换成XHTML
            OutputStream out = new FileOutputStream(htmlFile);
            XHTMLConverter.getInstance().convert(document, out, options);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Docx解析异常({}->{}):{}", wordPath, htmlPath, String.valueOf(e));
        }
        return flag;
    }


    /**
     * 编辑html 新增标签元素-解决偶尔出现的中文内容乱码
     * @param htmlPath
     * @return
     */
    public static boolean editHtml(String htmlPath) {
        boolean flag = false;

        BufferedReader br = null;
        BufferedWriter bw = null;
        try{
            // 读取html
            br = new BufferedReader(new FileReader(htmlPath));
            // 不使用按行读取(样式会有一定问题)
            String line;
            StringBuilder cb = new StringBuilder();
            while ((line=br.readLine()) != null){
                cb.append(line);
            }
            br.close();
            // 修改html
            String content = cb.toString();
            int i = content.indexOf("</head>");
            String newContent = new StringBuilder(content).insert(i, "<meta http-equiv='Content-Type' content='text/html;charset=utf-8'/>").toString();
            // 写入到html
            bw = new BufferedWriter(new FileWriter(htmlPath));
            bw.write(newContent);
            bw.close();
            flag = true;
        }catch (Exception e){
            e.printStackTrace();
            try {
                if (br != null){
                    br.close();
                }
                if (bw != null){
                    bw.close();
                }
            }catch (IOException ex){
                ex.printStackTrace();
            }
        }
        return flag;
    }

    public static void main(String[] args) {
        // 相关文档转换docx必须通过专业办公软件变更 直接更改后缀 本质未转换为docx 会出现异常
        word2Html("G:\\test\\download\\test.docx", "G:\\test\\download\\1.html");
        word2Html("G:\\test\\download\\test.doc", "G:\\test\\download\\2.html");
    }

}

image

image


标签:word,String,import,flag,html,poi,new
From: https://www.cnblogs.com/fsh19991001/p/17815861.html

相关文章

  • DocTemplateTool - 可根据模板生成word或pdf文件的工具
    你是否经常遇到这样的场景:产品运营有着大量的报告需求,或者给客户领导展现每周的运营报告?这些文档类的任务可以交给运营同事,他们负责文档排版和样式,你作为开发人员你只需要提供数据源,和一个映射表,告诉制作文档的人哪些字段可供使用。这样一来分工明确,减少了很多不必要的沟通成本。......
  • js怎么向html中的某个标签添加内容?举个简单能动的例子
    在JavaScript中,你可以通过多种方式向HTML元素添加内容。以下是两种常见的方法:innerHTML:这个属性用来获取或替换HTML元素的内容。appendChild():这个方法用来向节点添加最后一个子节点。以下是一个简单的例子,展示了如何使用这两种方法:假设你有这样一个HTML结构:<!DOCTYPEhtml......
  • Word还是markdown?
    Word还是markdown?使用markdown有四五年时间了,有欣喜,也有很过困扰。在这欣喜和困扰之后,我更不知道如何正确的使用markdown了一、我的身份和使用场景多年程序猿转产品两年多,18年开始接触markdown,凭着程序猿的学习干劲,markdown还不是轻轻松松拿下。在后续的工作生活中,经常markdo......
  • 21 个最佳 Javascript IDE 和代码编辑器 [CSS、HTML、JavaScript]
    这是我们挑选的21个最佳JavaScriptIDE和源代码编辑器。目录什么是IDE选择正确的开发环境时要寻找什么?免费的最佳JavascriptIDE最佳高级JavascriptIDE结论:最佳JavaScriptIDE是哪个?常见问题解答:最佳JavascriptIDE如今,Javascript在前端开发中越来越流行。您......
  • 分享一个Python 批量word转图片的方法
    我们的工作场景中每次上传word时都要把word文件先导出图片,然后一一上传系统,因为只有PNG图片能直接预览,且确保文本、图片和格式保持不变。但有时候遇到大的word文档,一个文档导出来可能都有几十张图片,这样效率实在太低。针对这种情况,我们选了Spire.DocforPython批量将word转图片......
  • Word中的“编辑>选择性粘贴>无格式文本”的快捷键
    手工制作无格式粘贴快捷键word2003,在菜单中选“编辑”--“选择性粘贴”--“无格式文本”,这个方法执行速度快,但操作步骤多,太麻烦。下面通过创建宏来解决这个问题,实现快捷键操作。这个过程分两步:一是建立一个实现“选择性粘贴”的宏,二是给这个宏指定键盘快捷键。一、创建“选择性粘贴......
  • 如何在 Word 2003 中恢复丢失的文件
    本文向您介绍可用于恢复丢失的文档的一些步骤。关于:打不开Word文件。搜索原文档单击“开始”,然后单击“搜索”。单击MicrosoftWindows资源管理器左侧的“搜索助理”中的“所有文件和文件夹”。在“全部或部分文件名:”框中,键入要查找的文件名。在“在这里寻找”框中,单击“我......
  • [HTML]特殊字符
    https://www.runoob.com/html/html-entities.html 显示结果描述实体名称实体编号 空格&nbsp;&#160;<小于号<&#60;>大于号>&#62;&和号&amp;&#38;"引号"&#34;'撇号 &apos;(IE不支持)&#39;¢分&......
  • BUUCTF_Crypto_WriteUp | password
    题目姓名:张三生日:19900315key格式为key{xxxxxxxxxx}分析标题是password,题目给的是key,猜测key里的内容应该就是张三的密码。题目给key的内容很认真地放了10个x,猜测flag内容是十位字符。而张三的姓名是2个字,给出的生日是8位,咱把姓名缩写和生日一组合,将得到的老......
  • Creating HTML table with vertically oriented text as table header 表头文字方向
    ASanoldquestion,thisismorelikeinfoorreminderaboutverticalmarginorpaddingin%thattakesparent'swidthasreference.Ifyouuseapseudoelementandvertical-padding,youmaybasiclydrawasquareboxor<td>:http://jsfiddle.n......