文档转换文件格式

Word 转 PDF

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* word 转 pdf
*
* @param word
* @param pdf
* @return
*/
public static boolean word2pdf(String word, String pdf) {
ActiveXComponent wps = null;
Dispatch doc = null;
// word 保存为 pdf 格式宏,值为 17
int fmt = 17;
long start = System.currentTimeMillis();
try {
/**
* 参数为 Word.Application:需要安装 Office
* 参数为 kwps.application:需要安装 WPS
* doc 转 pdf 时,用 Word.Application 报错
*/
wps = new ActiveXComponent("kwps.application");
wps.setProperty("visible", new Variant(false));
Dispatch docs = wps.getProperty("Documents").toDispatch();

// doc = Dispatch.invoke(docs, "Open", Dispatch.Method,
// new Object[]{word, new Variant(false),new Variant(true)},
// new int[1]).toDispatch();
Variant foo = Dispatch.call(docs, "Open", word, false, true);
if (foo.getvt() == 0) {
return false;
}
doc = foo.toDispatch();
// Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[]{pdf,new Variant(fmt)}, new int[1]);
Dispatch.call(doc, "SaveAs", pdf, fmt);
long end = System.currentTimeMillis();
System.out.println("耗时:" + (end - start) + "ms.");
return true;
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("转化出错:" + ex.getMessage());
return false;
} finally {
Dispatch.call(doc, "Close", false);
System.out.println("关闭WPS");
if (wps != null) {
wps.invoke("Quit", new Variant[]{});
}
}
}

参考:

Java 使用jacob实现doc转pdf(附带其他方法分析)

通过jacob实现office在线预览

Doc 与 Docx 格式互相转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public static void convertWordFmt(String srcPath, String descPath, int fmt) {
long startTime = System.currentTimeMillis();

// 实例化 ComThread 线程与 ActiveXComponent
ComThread.InitSTA();

/**
* 参数为 Word.Application:需要安装 Office
* 参数为 kwps.application:需要安装 WPS
* doc 转 docx 时,用 Word.Application 报错
*/
ActiveXComponent app = new ActiveXComponent("kwps.Application");

try {
// 文档隐藏时进行应用操作
app.setProperty("Visible", new Variant(false));
// 实例化模板 Document 对象
Dispatch document = app.getProperty("Documents").toDispatch();
// 打开 Document 进行另存为操作
Dispatch doc = Dispatch.invoke(document, "Open", Dispatch.Method,
new Object[]{srcPath, new Variant(true), new Variant(true)}, new int[1]).toDispatch();
Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[]{descPath, new Variant(fmt)}, new int[1]);
Dispatch.call(doc, "Close", new Variant(false));
} finally {
// 释放线程与 ActiveXComponent
app.invoke("Quit", new Variant[]{});
ComThread.Release();
}

System.out.println("convert word format successfully, " +
"take " + (System.currentTimeMillis() - startTime) / 1000 + " seconds.");
}

参考:JAVA实现Doc与Docx互转

分享到:
Disqus 加载中...

如果长时间无法加载,请针对 disq.us | disquscdn.com | disqus.com 启用代理