整体思路参考http://www.iteye.com/topic/588050
上面的这篇文章使用jacob将word转换成HTML的,利用的是Word的另存为功能,在Office 2007 SP2之后,Office就可以另存为PDF了,可以使用这个方法将office另存为PDF文档。
具体代码可以参考上文里面的,另存为哪种类型是由new variant()里面的参数决定的。
Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {htmlfile, new Variant(WORD_HTML) }, new int[1]);
new Variant(),这里面的根据传入的参数不同,可以另存为不同的类型,但是在网上搜索了一个并没有找到有关这个参数类型的一个说明,自己尝试了一下,结果如下:
0 | Doc |
1 | Dot |
2-5 | Txt |
6 | Rtf |
7 | Txt |
8、10 | htm |
11 | Xml |
12、16 | Docx |
13 | Docm |
14 | Dotx |
15 | Dotm |
17 | |
我使用的是office 2010,不同版本的对应的应该不一样,我是写了这一小段程序来测试另存为的类型的。
public class JacobTest {
public static void wordToPDF(String docfile, String toFile,int type) {
ActiveXComponent app = new ActiveXComponent("Word.Application"); // 启动word
try {
app.setProperty("Visible", new Variant(false));
Dispatch docs = app.getProperty("Documents").toDispatch();
Dispatch doc = Dispatch.invoke(
docs,
"Open",
Dispatch.Method,
new Object[] { docfile, new Variant(false),
new Variant(true) }, new int[1]).toDispatch();
//new Variant(type),这里面的type的决定另存为什么类型的文件
Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
toFile, new Variant(type) }, new int[1]);
Variant f = new Variant(false);
Dispatch.call(doc, "Close", f);
} catch (Exception e) {
e.printStackTrace();
} finally {
app.invoke("Quit", new Variant[] {});
}
}
public static void main(String[] args) {
//源文件全路径
String docfile ="D:\\服务实施描述报告(企业门户).docx";
for (int i = 0; i < 18; i++) {
//些路径test为实际存在的目录,s后面为要另存为的文件名
String toFile="d:\\test\\s"+i;
wordToPDF(docfile, toFile,i);
}
}
}