Windows系统下

1.下载所需插件和jar包

SaveAsPDFandXPS(微软自带office转PDF、XPS):http://www.microsoft.com/zh-cn/download/details.aspx?id=7

    jacob (jar包):https://sourceforge.net/projects/jacob-project/

2. 配置

① 按步骤安装 SaveAsPDFandXPS

② jacob 下载后打开,如下

Word转PDF(SaveAsPDFandXPS + jacob)-LMLPHP

将红色的.dll文件放到jdk/bin/目录下

绿色的jar包直接导入项目

(注:jacob是1.19 ,jdk是1.8,之前用1.7jdk会报版本不兼容的错~)

3. 代码

package com.sinosoft;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.sun.istack.internal.logging.Logger;
import org.junit.Test; import java.io.File; public class Main {
protected final Logger cLogger= Logger.getLogger(getClass());
private static final int wdFormatPDF = 17;
@Test
public void test1(){
cLogger.info("这是一个Xjb测试的test..");
wordToPDF();
} public static void wordToPDF(){ ActiveXComponent app = null;
Dispatch doc = null;
try {
app = new ActiveXComponent("Word.Application");
app.setProperty("Visible", new Variant(false));
Dispatch docs = app.getProperty("Documents").toDispatch(); String startFile = "E:\\lcb\\LearningMaterials\\xjblearn\\测试word" + ".doc";
String overFile = "E:\\lcb\\LearningMaterials\\xjblearn\\转换pdf" + ".pdf"; doc = Dispatch.call(docs, "Open" , startFile).toDispatch();
File tofile = new File(overFile);
if (tofile.exists()) {
tofile.delete();
}
Dispatch.call(doc,"SaveAs", overFile, wdFormatPDF);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
Dispatch.call(doc,"Close",false);
if (app != null)
app.invoke("Quit", new Variant[] {});
}
//结束后关闭进程
ComThread.Release();
}

4.测试结果

Word转PDF(SaveAsPDFandXPS + jacob)-LMLPHP

Word转PDF(SaveAsPDFandXPS + jacob)-LMLPHP

04-14 09:16