java word文档 转 html文件

简介: 一、简介   一般word文件后缀有doc、docx两种。docx是office word 2007以及以后版本文档的扩展名;doc是office word 2003文档保存的扩展名。对于这两种格式的word转换成html需要使用不同的方法。

一、简介
  一般word文件后缀有doc、docx两种。docx是office word 2007以及以后版本文档的扩展名;doc是office word 2003文档保存的扩展名。对于这两种格式的word转换成html需要使用不同的方法。
对于docx格式的文档使用xdocreport进行转换。依赖如下:

<dependency>
    <groupId>fr.opensagres.xdocreport</groupId>
    <artifactId>fr.opensagres.xdocreport.document</artifactId>
    <version>1.0.5</version>
</dependency>
<dependency>  
    <groupId>fr.opensagres.xdocreport</groupId>  
    <artifactId>org.apache.poi.xwpf.converter.xhtml</artifactId>  
    <version>1.0.5</version>  
</dependency>

对于docx格式的文档使用poi进行转换。依赖如下:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.12</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>3.12</version>
</dependency>

二:示例
  代码示例如下:

  1 package com.test.word;
  2 
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.FileNotFoundException;
  6 import java.io.FileOutputStream;
  7 import java.io.IOException;
  8 import java.io.InputStream;
  9 import java.io.OutputStream;
 10 
 11 import javax.xml.parsers.DocumentBuilderFactory;
 12 import javax.xml.parsers.ParserConfigurationException;
 13 import javax.xml.transform.OutputKeys;
 14 import javax.xml.transform.Transformer;
 15 import javax.xml.transform.TransformerException;
 16 import javax.xml.transform.TransformerFactory;
 17 import javax.xml.transform.dom.DOMSource;
 18 import javax.xml.transform.stream.StreamResult;
 19 
 20 import org.apache.poi.hwpf.HWPFDocument;
 21 import org.apache.poi.hwpf.converter.PicturesManager;
 22 import org.apache.poi.hwpf.converter.WordToHtmlConverter;
 23 import org.apache.poi.hwpf.usermodel.PictureType;
 24 import org.apache.poi.xwpf.converter.core.FileImageExtractor;
 25 import org.apache.poi.xwpf.converter.core.FileURIResolver;
 26 import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
 27 import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
 28 import org.apache.poi.xwpf.usermodel.XWPFDocument;
 29 import org.junit.Test;
 30 import org.w3c.dom.Document;
 31 
 32 /**
 33  * word 转换成html
 34  */
 35 public class WordToHtml {
 36     
 37     /**
 38      * 2007版本word转换成html
 39      * @throws IOException
 40      */
 41     @Test 
 42     public void Word2007ToHtml() throws IOException {
 43         String filepath = "C:/test/";
 44         String fileName = "滕王阁序2007.docx";
 45         String htmlName = "滕王阁序2007.html";
 46         final String file = filepath + fileName;
 47         File f = new File(file);  
 48         if (!f.exists()) {  
 49             System.out.println("Sorry File does not Exists!");  
 50         } else {  
 51             if (f.getName().endsWith(".docx") || f.getName().endsWith(".DOCX")) {  
 52                   
 53                 // 1) 加载word文档生成 XWPFDocument对象  
 54                 InputStream in = new FileInputStream(f);  
 55                 XWPFDocument document = new XWPFDocument(in);  
 56   
 57                 // 2) 解析 XHTML配置 (这里设置IURIResolver来设置图片存放的目录)  
 58                 File imageFolderFile = new File(filepath);  
 59                 XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(imageFolderFile));  
 60                 options.setExtractor(new FileImageExtractor(imageFolderFile));  
 61                 options.setIgnoreStylesIfUnused(false);  
 62                 options.setFragment(true);  
 63                   
 64                 // 3) 将 XWPFDocument转换成XHTML  
 65                 OutputStream out = new FileOutputStream(new File(filepath + htmlName));  
 66                 XHTMLConverter.getInstance().convert(document, out, options);  
 67                 
 68                 //也可以使用字符数组流获取解析的内容
 69 //                ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
 70 //                XHTMLConverter.getInstance().convert(document, baos, options);  
 71 //                String content = baos.toString();
 72 //                System.out.println(content);
 73 //                 baos.close();
 74             } else {  
 75                 System.out.println("Enter only MS Office 2007+ files");  
 76             }  
 77         }  
 78     }  
 79     
 80     /**
 81      * /**
 82      * 2003版本word转换成html
 83      * @throws IOException
 84      * @throws TransformerException
 85      * @throws ParserConfigurationException
 86      */
 87     @Test 
 88     public void Word2003ToHtml() throws IOException, TransformerException, ParserConfigurationException {
 89         String filepath = "C:/test/";
 90         final String imagepath = "C:/test/image/";
 91         String fileName = "滕王阁序2003.doc";
 92         String htmlName = "滕王阁序2003.html";
 93         final String file = filepath + fileName;
 94         InputStream input = new FileInputStream(new File(file));
 95         HWPFDocument wordDocument = new HWPFDocument(input);
 96         WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
 97         //设置图片存放的位置
 98         wordToHtmlConverter.setPicturesManager(new PicturesManager() {
 99             public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
100                 File imgPath = new File(imagepath);
101                 if(!imgPath.exists()){//图片目录不存在则创建
102                     imgPath.mkdirs();
103                 }
104                 File file = new File(imagepath + suggestedName);
105                 try {
106                     OutputStream os = new FileOutputStream(file);
107                     os.write(content);
108                     os.close();
109                 } catch (FileNotFoundException e) {
110                     e.printStackTrace();
111                 } catch (IOException e) {
112                     e.printStackTrace();
113                 }
114                 return imagepath + suggestedName;
115             }
116         });
117         
118         //解析word文档
119         wordToHtmlConverter.processDocument(wordDocument);
120         Document htmlDocument = wordToHtmlConverter.getDocument();
121         
122         File htmlFile = new File(filepath + htmlName);
123         OutputStream outStream = new FileOutputStream(htmlFile);
124         
125         //也可以使用字符数组流获取解析的内容
126 //        ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
127 //        OutputStream outStream = new BufferedOutputStream(baos);
128 
129         DOMSource domSource = new DOMSource(htmlDocument);
130         StreamResult streamResult = new StreamResult(outStream);
131 
132         TransformerFactory factory = TransformerFactory.newInstance();
133         Transformer serializer = factory.newTransformer();
134         serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
135         serializer.setOutputProperty(OutputKeys.INDENT, "yes");
136         serializer.setOutputProperty(OutputKeys.METHOD, "html");
137         
138         serializer.transform(domSource, streamResult);
139 
140         //也可以使用字符数组流获取解析的内容
141 //        String content = baos.toString();
142 //        System.out.println(content);
143 //        baos.close();
144         outStream.close();
145     }
146 }

  运行生存文件结果如下:

  

   

目录
相关文章
|
2月前
|
Java Unix Go
【Java】(8)Stream流、文件File相关操作,IO的含义与运用
Java 为 I/O 提供了强大的而灵活的支持,使其更广泛地应用到文件传输和网络编程中。!但本节讲述最基本的和流与 I/O 相关的功能。我们将通过一个个例子来学习这些功能。
180 1
|
3月前
|
XML 前端开发 C#
C#编程实践:解析HTML文档并执行元素匹配
通过上述步骤,可以在C#中有效地解析HTML文档并执行元素匹配。HtmlAgilityPack提供了一个强大而灵活的工具集,可以处理各种HTML解析任务。
192 19
|
5月前
|
存储 Java 编译器
深入理解Java虚拟机--类文件结构
本内容介绍了Java虚拟机与Class文件的关系及其内部结构。Class文件是一种与语言无关的二进制格式,包含JVM指令集、符号表等信息。无论使用何种语言,只要能生成符合规范的Class文件,即可在JVM上运行。文章详细解析了Class文件的组成,包括魔数、版本号、常量池、访问标志、类索引、字段表、方法表和属性表等,并说明其在Java编译与运行过程中的作用。
139 0
|
5月前
|
存储 人工智能 Java
java之通过Http下载文件
本文介绍了使用Java实现通过文件链接下载文件到本地的方法,主要涉及URL、HttpURLConnection及输入输出流的操作。
314 0
|
5月前
|
监控 Java API
Java语言按文件创建日期排序及获取最新文件的技术
这段代码实现了文件创建时间的读取、文件列表的获取与排序以及获取最新文件的需求。它具备良好的效率和可读性,对于绝大多数处理文件属性相关的需求来说足够健壮。在实际应用中,根据具体情况,可能还需要进一步处理如访问权限不足、文件系统不支持某些属性等边界情况。
257 14
|
6月前
|
存储 Java 数据安全/隐私保护
Java技术栈揭秘:Base64加密和解密文件的实战案例
以上就是我们今天关于Java实现Base64编码和解码的实战案例介绍。希望能对你有所帮助。还有更多知识等待你去探索和学习,让我们一同努力,继续前行!
468 5
|
6月前
|
网络协议 安全 Java
实现Java语言的文件断点续传功能的技术方案。
像这样,我们就完成了一项看似高科技、实则亲民的小工程。这样的技术实现不仅具备实用性,也能在面对网络不稳定的挑战时,稳稳地、不失乐趣地完成工作。
346 0
|
8月前
|
API
Postman 可以将文档导出为 HTML/Markdown 吗?
Postman 没有提供直接将你的文档导出为 HTML 或 Markdown 的途径。太糟糕了
|
9月前
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
|
10月前
|
Java API 数据处理
深潜数据海洋:Java文件读写全面解析与实战指南
通过本文的详细解析与实战示例,您可以系统地掌握Java中各种文件读写操作,从基本的读写到高效的NIO操作,再到文件复制、移动和删除。希望这些内容能够帮助您在实际项目中处理文件数据,提高开发效率和代码质量。
245 4