当前位置:首页 » 编程语言 » word转htmljava

word转htmljava

发布时间: 2023-08-21 20:54:38

java 有关word,excel,pdf转换成html 有几种方式

java将Word/Excel/PDF文件转换成HTML整理

项目开发过程中,需求涉及到了各种文档转换为HTML或者网页易显示格式,现在将实现方式整理如下:
一、使用Jacob转换Word,Excel为HTML

“JACOB一个Java-COM中间件.通过这个组件你可以在Java应用程序中调用COM组件和Win32 libraries。”

首先下载Jacob包,JDK1.5以上需要使用Jacob1.9版本(JDK1.6尚未测试),与先前的Jacob1.7差别不大

1、将压缩解压后,Jacob.jar添加到Libraries中;

2、将Jacob.dll放至“WINDOWS\SYSTEM32”下面。

需要注意的是:
【使用IDE启动Web服务器时,系统读取不到Jacob.dll,例如用MyEclipse启动Tomcat,就需要将dll文件到MyEclipse安装目录的“jre\bin”下面。
一般系统没有加载到Jacob.dll文件时,报错信息为:“java.lang.UnsatisfiedLinkError: no jacob in java.library.path”】

新建类:
1public class JacobUtil
2{
3 public static final int WORD_HTML = 8;
4
5 public static final int WORD_TXT = 7;
6
7 public static final int EXCEL_HTML = 44;
8
9 /** *//**
10 * WORD转HTML
11 * @param docfile WORD文件全路径
12 * @param htmlfile 转换后HTML存放路径
13 */
14 public static void wordToHtml(String docfile, String htmlfile)
15 {
16 ActiveXComponent app = new ActiveXComponent("Word.Application"); // 启动word
17 try
18 {
19 app.setProperty("Visible", new Variant(false));
20 Dispatch docs = app.getProperty("Documents").toDispatch();
21 Dispatch doc = Dispatch.invoke(
22 docs,
23 "Open",
24 Dispatch.Method,
25 new Object[] { docfile, new Variant(false),
26 new Variant(true) }, new int[1]).toDispatch();
27 Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
28 htmlfile, new Variant(WORD_HTML) }, new int[1]);
29 Variant f = new Variant(false);
30 Dispatch.call(doc, "Close", f);
31 }
32 catch (Exception e)
33 {
34 e.printStackTrace();
35 }
36 finally
37 {
38 app.invoke("Quit", new Variant[] {});
39 }
40 }
41
42 /** *//**
43 * EXCEL转HTML
44 * @param xlsfile EXCEL文件全路径
45 * @param htmlfile 转换后HTML存放路径
46 */
47 public static void excelToHtml(String xlsfile, String htmlfile)
48 {
49 ActiveXComponent app = new ActiveXComponent("Excel.Application"); // 启动word
50 try
51 {
52 app.setProperty("Visible", new Variant(false));
53 Dispatch excels = app.getProperty("Workbooks").toDispatch();
54 Dispatch excel = Dispatch.invoke(
55 excels,
56 "Open",
57 Dispatch.Method,
58 new Object[] { xlsfile, new Variant(false),
59 new Variant(true) }, new int[1]).toDispatch();
60 Dispatch.invoke(excel, "SaveAs", Dispatch.Method, new Object[] {
61 htmlfile, new Variant(EXCEL_HTML) }, new int[1]);
62 Variant f = new Variant(false);
63 Dispatch.call(excel, "Close", f);
64 }
65 catch (Exception e)
66 {
67 e.printStackTrace();
68 }
69 finally
70 {
71 app.invoke("Quit", new Variant[] {});
72 }
73 }
74
75}
76
当时我在找转换控件时,发现网易也转载了一偏关于Jacob使用帮助,但其中出现了比较严重的错误:String htmlfile = "C:\\AA";
只指定到了文件夹一级,正确写法是String htmlfile = "C:\\AA\\xxx.html";

到此WORD/EXCEL转换HTML就已经差不多了,相信大家应该很清楚了:)

二、使用XPDF将PDF转换为HTML

1、下载xpdf最新版本,地址:http://www.foolabs.com/xpdf/download.html
我下载的是xpdf-3.02pl2-win32.zip

2、下载中文支持包
我下载的是xpdf-chinese-simplified.tar.gz

3、下载pdftohtml支持包
地址:http://sourceforge.net/projects/pdftohtml/
我下载的是:pdftohtml-0.39-win32.tar.gz

4、解压调试
1) 先将xpdf-3.02pl2-win32.zip解压,解压后的内容可根据需要进行删减,如果只需要转换为txt格式,其他的exe文件可以删除,只保留pdftotext.exe,以此类推;
2) 然后将xpdf-chinese-simplified.tar.gz解压到刚才xpdf-3.02pl2-win32.zip的解压目录;
3) 将pdftohtml-0.39-win32.tar.gz解压,pdftohtml.exe解压到xpdf-3.02pl2-win32.zip的解压目录;
4) 目录结构:
+---[X:\xpdf]
|-------各种转换用到的exe文件
|
|-------xpdfrc
|
+------[X:\xpdf\xpdf-chinese-simplified]
|
|
+-------很多转换时需要用到的字符文件

xpdfrc:此文件是用来声明转换字符集对应路径的文件

5) 修改xpdfrc文件(文件原名为sample-xpdfrc)
修改文件内容为:
Txt代码

#----- begin Chinese Simplified support package
cidToUnicode Adobe-GB1 xpdf-chinese-simplified\Adobe-GB1.cidToUnicode
unicodeMap ISO-2022-CN xpdf-chinese-simplified\ISO-2022-CN.unicodeMap
unicodeMap EUC-CN xpdf-chinese-simplified\EUC-CN.unicodeMap
unicodeMap GBK xpdf-chinese-simplified\GBK.unicodeMap
cMapDir Adobe-GB1 xpdf-chinese-simplified\CMap
toUnicodeDir xpdf-chinese-simplified\CMap
fontDir C:\WINDOWS\Fonts
displayCIDFontTT Adobe-GB1 C:\WINDOWS\Fonts\simhei.ttf
#----- end Chinese Simplified support package

6) 创建bat文件pdftohtml.bat(放置的路径不能包含空格)
内容为:
Txt代码

@echo off
set folderPath=%1
set filePath=%2
cd /d %folderPath%
pdftohtml -enc GBK %filePath%
exit
7) 创建类

JAVA代码

public class ConvertPdf
{
private static String INPUT_PATH;
private static String PROJECT_PATH;

public static void convertToHtml(String file, String project)
{
INPUT_PATH = file;
PROJECT_PATH = project;
if(checkContentType()==0)
{
toHtml();
}
}

private static int checkContentType()
{
String type = INPUT_PATH.substring(INPUT_PATH.lastIndexOf(".") + 1, INPUT_PATH.length())
.toLowerCase();
if (type.equals("pdf"))
return 0;
else
return 9;
}

private static void toHtml()
{
if(new File(INPUT_PATH).isFile())
{
try
{
String cmd = "cmd /c start X:\\pdftohtml.bat \"" + PROJECT_PATH + "\" \"" + INPUT_PATH + "\"";
Runtime.getRuntime().exec(cmd);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

}

㈡ Java怎么操作OpenOffice创建word文档并向其设置内容

将Word转Html的原理是这样的:
1、客户上传Word文档到服务器
2、服务器调用OpenOffice程序打开上传的Word文档
3、OpenOffice将Word文档另存为Html格式
4、Over
至此可见,这要求服务器端安装OpenOffice软件,其实也可以是MS Office,不过OpenOffice的优势是跨平台,你懂的。恩,说明一下,本文的测试基于 MS Win7 Ultimate X64 系统。
下面就是规规矩矩的实现。
1、下载OpenOffice,
2、下载Jodconverter 这是一个开启OpenOffice进行格式转化的第三方jar包。
3、泡杯热茶,等待下载。

4、安装OpenOffice,安装结束后,调用cmd,启动OpenOffice的一项服务:C:\Program Files (x86)\OpenOffice.org 3\program>soffice -headless -accept="socket,port=8100;urp;"

5、打开eclipse
6、喝杯热茶,等待eclipse打开。
7、新建eclipse项目,导入Jodconverter/lib 下得jar包。

* commons-io
* jodconverter
* juh
* jurt
* ridl
* slf4j-api
* slf4j-jdk14
* unoil
* xstream

8、Coding...

查看代码

package com.mzule.doc2html.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;

/**
* 将Word文档转换成html字符串的工具类
*
* @author MZULE
*
*/
public class Doc2Html {

public static void main(String[] args) {
System.out
.println(toHtmlString(new File("C:/test/test.doc"), "C:/test"));
}

/**
* 将word文档转换成html文档
*
* @param docFile
* 需要转换的word文档
* @param filepath
* 转换之后html的存放路径
* @return 转换之后的html文件
*/
public static File convert(File docFile, String filepath) {
// 创建保存html的文件
File htmlFile = new File(filepath + "/" + new Date().getTime()
+ ".html");
// 创建Openoffice连接
OpenOfficeConnection con = new SocketOpenOfficeConnection(8100);
try {
// 连接
con.connect();
} catch (ConnectException e) {
System.out.println("获取OpenOffice连接失败...");
e.printStackTrace();
}
// 创建转换器
DocumentConverter converter = new OpenOfficeDocumentConverter(con);
// 转换文档问html
converter.convert(docFile, htmlFile);
// 关闭openoffice连接
con.disconnect();
return htmlFile;
}

/**
* 将word转换成html文件,并且获取html文件代码。
*
* @param docFile
* 需要转换的文档
* @param filepath
* 文档中图片的保存位置
* @return 转换成功的html代码
*/
public static String toHtmlString(File docFile, String filepath) {
// 转换word文档
File htmlFile = convert(docFile, filepath);
// 获取html文件流
StringBuffer htmlSb = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(htmlFile)));
while (br.ready()) {
htmlSb.append(br.readLine());
}
br.close();
// 删除临时文件
htmlFile.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// HTML文件字符串
String htmlStr = htmlSb.toString();
// 返回经过清洁的html文本
return clearFormat(htmlStr, filepath);
}

/**
* 清除一些不需要的html标记
*
* @param htmlStr
* 带有复杂html标记的html语句
* @return 去除了不需要html标记的语句
*/
protected static String clearFormat(String htmlStr, String docImgPath) {
// 获取body内容的正则
String bodyReg = "<BODY .*</BODY>";
Pattern bodyPattern = Pattern.compile(bodyReg);
Matcher bodyMatcher = bodyPattern.matcher(htmlStr);
if (bodyMatcher.find()) {
// 获取BODY内容,并转化BODY标签为DIV
htmlStr = bodyMatcher.group().replaceFirst("<BODY", "<DIV")
.replaceAll("</BODY>", "</DIV>");
}
// 调整图片地址
htmlStr = htmlStr.replaceAll("<IMG SRC=\"", "<IMG SRC=\"" + docImgPath
+ "/");
// 把<P></P>转换成</div></div>保留样式
// content = content.replaceAll("(<P)([^>]*>.*?)(<\\/P>)",
// "<div$2</div>");
// 把<P></P>转换成</div></div>并删除样式
htmlStr = htmlStr.replaceAll("(<P)([^>]*)(>.*?)(<\\/P>)", "<p$3</p>");
// 删除不需要的标签
htmlStr = htmlStr
.replaceAll(
"<[/]?(font|FONT|span|SPAN|xml|XML|del|DEL|ins|INS|meta|META|[ovwxpOVWXP]:\\w+)[^>]*?>",
"");
// 删除不需要的属性
htmlStr = htmlStr
.replaceAll(
"<([^>]*)(?:lang|LANG|class|CLASS|style|STYLE|size|SIZE|face|FACE|[ovwxpOVWXP]:\\w+)=(?:'[^']*'|\"\"[^\"\"]*\"\"|[^>]+)([^>]*)>",
"<$1$2>");
return htmlStr;
}

}

㈢ 怎样用Java把word文档转换为html文档

可以通过Spire.Doc for Java进行转换。

首先需要安装Spire.Doc for Java。可在 Java 程序中添加 Spire.Doc for Java 文件作为依赖项。JAR 文件可以从此链接下载。 如果您使用 Maven,则可以将以下代码添加到项目的 pom.xml 文件中,从而轻松地在应用程序中导入 JAR 文件。

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository></repositories><dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc</artifactId>
<version>5.2.3</version>
</dependency></dependencies>

Java代码如下:

mport com.spire.doc.*;public class WordtoHtml {
public static void main(String[] args) {
//实例化Document类的对象
Document doc = new Document();

//加载Word文档
doc.loadFromFile("inputfile.docx");

//保存为HTML格式
doc.saveToFile("ToHtml.html",FileFormat.Html);
doc.dispose();
}

}

希望对您有帮助。

㈣ Java程序调用 openoffice,将doc文件转Html文件,但转换完格式都变成居左边

1、到官网下载Jacob,
2、将压缩包解压后,Jacob.jar添加到Libraries中(先复制到项目目录中,右键单击jar包选择BuildPath—>AddtoBuildPath);
3、将Jacob.dll放至当前项目所用到的“jrein”下面(比如Eclipse正在用的Jre路径是C:Javajdk1.7.0_17jrein)。
Ps:按照上面的步骤配置的,基本没有问题,但是有些电脑可能还会报错,比如:java.lang.UnsatisfiedLinkError:nojacobinjava.library.path,这是系统没有加载到jacob.dll,网上解决方法是将Jacob.dll放至“WINDOWSSYSTEM32”下面。

Java代码:
publicclassJacobUtil{
//8代表word保存成html
publicstaticfinalintWORD_HTML=8;
publicstaticvoidmain(String[]args){
Stringdocfile="C:\Users\无名\Desktop\xxx.doc";
Stringhtmlfile="C:\Users\无名\Desktop\xxx.html";
JacobUtil.wordToHtml(docfile,htmlfile);
}
/**
*WORD转HTML
*@paramdocfileWORD文件全路径
*@paramhtmlfile转换后HTML存放路径
*/
publicstaticvoidwordToHtml(Stringdocfile,Stringhtmlfile)
{
//启动word应用程序(MicrosoftOfficeWord2003)
ActiveXComponentapp=newActiveXComponent("Word.Application");
System.out.println("*****正在转换...*****");
try
{
//设置word应用程序不可见
app.setProperty("Visible",newVariant(false));
//documents表示word程序的所有文档窗口,(word是多文档应用程序)
Dispatchdocs=app.getProperty("Documents").toDispatch();
//打开要转换的word文件
Dispatchdoc=Dispatch.invoke(
docs,
"Open",
Dispatch.Method,
newObject[]{docfile,newVariant(false),
newVariant(true)},newint[1]).toDispatch();
//作为html格式保存到临时文件
Dispatch.invoke(doc,"SaveAs",Dispatch.Method,newObject[]{
htmlfile,newVariant(WORD_HTML)},newint[1]);
//关闭word文件
Dispatch.call(doc,"Close",newVariant(false));
}catch(Exceptione){
e.printStackTrace();
}finally{
//关闭word应用程序
app.invoke("Quit",newVariant[]{});
}
System.out.println("*****转换完毕********");
}
}

㈤ java使用jacob将word转换为html,如何设置转换后html的编码格式。我想要utf-8的,不要gb2312。

强制转码~~
line你要转的内容
line=new String(line.getBytes("gb2312"),"utf-8");代码是我凭记忆写的,应该没问题
或者你在写之前。先写一个HTML页面编码的代码 。把页面的格式设置成utf-8

热点内容
死锁避免的算法 发布:2025-02-05 04:43:07 浏览:579
python查文档 发布:2025-02-05 04:27:49 浏览:496
javaxmldom 发布:2025-02-05 04:27:40 浏览:9
linux修改内存大小 发布:2025-02-05 04:26:05 浏览:997
ftp命令复制文件 发布:2025-02-05 04:26:00 浏览:303
python好用的ide 发布:2025-02-05 04:14:18 浏览:516
id密码开头是多少 发布:2025-02-05 04:11:51 浏览:101
数据结构c语言ppt 发布:2025-02-05 04:11:45 浏览:43
如何用学习机配置的笔写字 发布:2025-02-05 04:09:15 浏览:395
5岁编程 发布:2025-02-05 04:06:21 浏览:653