使用jacob实现word转pdf WPS版

准备:

  • java用到的jar包:jacob-1.18
  • jacob-1.18-x64.dll、jacob-1.18-x86.dll

根据您的操作系统的需要将jacob-1.18-x64.dll或jacob-1.18-x86.dll放置你的jdk/jre的bin目录下

在你的项目中引入jacob-1.18 jar

本下载压缩包内包含jacob-1.18和jacob-1.18-x64.dll、jacob-1.18-x86.dll

下载:官网

补充:

  • 需要安装wps

  • jacob不得低于1.18

  • jdk1.8

示例:

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.yzw;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import java.io.File;

/**
* @author yzw
* @date 2021/1/1
*/
public class Test1111 {
static final int wdDoNotSaveChanges = 0;// 不保存待定的更改。
static final int wdFormatPDF = 17;// PDF 格式

public void toPDF(String filename, String toFilename){

System.out.println("启动Word");
long start = System.currentTimeMillis();
ActiveXComponent app = null;
try {
app = new ActiveXComponent("KWPS.Application");
app.setProperty("Visible", false);

Dispatch docs = app.getProperty("Documents").toDispatch();
System.out.println("打开文档" + filename);
Dispatch doc = Dispatch.call(docs,//
"Open", //
filename,// FileName
false,// ConfirmConversions
true // ReadOnly
).toDispatch();

System.out.println("转换文档到PDF" + toFilename);
File tofile = new File(toFilename);
if (tofile.exists()) {
tofile.delete();
}
Dispatch.call(doc,//
"SaveAs", //
toFilename, // FileName
wdFormatPDF);

Dispatch.call(doc, "Close", false);
long end = System.currentTimeMillis();
System.out.println("转换完成..用时:" + (end - start) + "ms.");
} catch (Exception e) {
System.out.println("========Error:文档转换失败:" + e.getMessage());
} finally {
if (app != null)
app.invoke("Quit", wdDoNotSaveChanges);
}

}
public static void main(String[] args) throws Exception {

String wordFile ="C:\\Users\\27184\\Desktop\\项目\\新建文件夹\\CG20120719.docx";
String pdfFile = "C:\\Users\\27184\\Desktop\\项目\\新建文件夹\\成功.pdf";

Test1111 test1111 = new Test1111();
Long startTime = System.currentTimeMillis();
test1111.toPDF(wordFile, pdfFile);
Long endTime = System.currentTimeMillis();
System.out.println("office转换pdf耗时:"+ (endTime - startTime) + "毫秒。");
System.out.println();
System.out.println("Office 转 PDF成功!");
}

}