java 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 }

  运行生存文件结果如下:

  

   

时间: 2024-08-01 14:44:17

java word文档 转 html文件的相关文章

允许嵌入到PDF,Word文档和其他文件的条形码控件UPC/EAN Barcode Font Advantage Package

IDAutomation的UPC/EAN Barcode Font Advantage Package是一个先进的字体产品,它所用的工具,宏和源代码可以使用一个单一的字体文件来创建UCC-12, UPCA, UPCE, EAN8, EAN13, JAN, ISBN 和Bookland条形码.该字体满足ANSI, ISO和IEC 2000规格说明要求(ISO 15420:2000). 具体功能: 为了创建合适的UPC和EAN条形码类型,打印的字符必须要从UPC/EAN条形码字体数据表上定义的表格上

POI实现word文档转html文件

POI word文件转html package com.feiruo.officeConvert; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.ut

批量转换word文档到pdf文件

最近在整理每周的工作记录.因为每周的工作记录大都是单独的word文件,有时候忘记了也不容易找出来,一个个打开查找太费劲,因此想着把这些文件通过word2016的另存为功能转换为pdf,然后永Acrobat合并起来. 思路如下: (1)通过Python代码搜索指定输入目录下的所有word文档,调用word COM接口,将文件转存为pdf文件到指定输出目录: (2)利用Acrobat将输出的目录中所有的pdf合并成单个pdf文件供存档查阅. 步骤(1)的代码如下: 1 import os 2 #im

如何在PowerDesigner将PDM导出生成WORD文档或者html文件

a)         使用PowerDesigner打开pdm文件 b)         点击Report Temlates 制作模板 点击PowerDesigner菜单栏“Report” -> “Report Templates” c)         选择模板数据项 完成步骤a),得到如下界面,左右2个区,Aavailable区域中选择你想要在WORD文档中展示的数据项,这里我们选择List of Tables,和List of Table Columns[数据表格信息] d)       

Java 使用 jacob 将 word 文档转换为 pdf 文件

网上查询了许许多多的博客,说利用 poi.iText.Jsoup.jdoctopdf.使用 jodconverter 来调用 openOffice 的服务来转换等等,我尝试了很多种,但要么显示不完全,要么可是可能有问题,使用这个 jacob 的方法我最开始是最不想用的,因为它要导入 dll 文件,但最后我还是选择了使用该方法,原因是感觉转换后的 pdf 文件简直就是完美. jacob 缺点:需要 window 环境,而且速度是最慢的需要安装 msofficeWord 以及 SaveAsPDFan

转换Word文档为PDF文件

1.使用 Office COM组件的Microsoft.Office.Interop.word.dll库 该方法需要在电脑上安装Office软件,并且需要Office支持转换为PDF格式,如果不支持,从官网下载一个SaveAsPDFandXPS.exe插件 Interop.word程序集可以通过Nuget程序包获取,实现代码如下: public bool WordToPDF2(string sourcePath) { bool result = false; Word.Application a

JAVA生成Word文档(经过测试)

首先告诉大家这篇文章的原始出处:http://www.havenliu.com/java/514.html/comment-page-1#comment-756 我也是根据他所描述完成的,但是有一些地方有点模糊,不容易弄出来.所以,我另外写一篇,让大家少走一些弯路. 上图:是Word文档中的内容,也就是模板,为了下面步鄹做铺垫,所以在需要输入数据的地方改成了拼音, 将word文档另存为xml文件. 接下来,上面写的拼音就起到作用了. 打开xml文件.搜索 title. 将Title 改为 ${t

java使用freemarker生成word文档

1.原料 开源jar包freemarker.eclipse.一份模板word文档 2.首先设计模板word文档 一般,通过程序输出的word文档的格式是固定的,例如建立一个表格,将表格的标题写好,表格的内容使用不同的标记标好,设计好word后,将word文档另存为xml文件(注:只有word2003 以上的版本可以),使用xml工具打开文件,将要输出到word的内容使用${XX}替换,保存后将文件直接改为tdl后缀 3.使用eclipse编写程序 1)获得一个Configuration实例,并为

如何将PDF文件转换为能编辑的Word文档

近几年PDF文档越来越普遍化,原因就是word文档保存的文件有可能会因为电脑的差异而打不开,或者在显示上会有差异,给使用者造成不必要的麻烦.PDF能保存写作者想要的效果,将word文档储存为PDF是一个不错的选择.但是在需要编辑的时候又怎么把PDF文档转换成能编辑的word文档呢? 不是所有PDF文件都可以转换为能编辑的word文档,对于扫描的PDF文件只能转为图片内容的word文档,被加密的PDF文件如果不去除密码那么转换为word后也是图片内容. 方法A:要转换PDF文档的格式可以用在线的方