使用jacob将word转为pdf时报com.jacob.com.ComFailException: Invoke of: SaveAs ...

代码如下:

public class WordToPdf {

	static final int wdFormatPDF = 17;// PDF 格式

	public void wordToPDF(String sfileName, String toFileName) {

		System.out.println("启动Word...");
		long start = System.currentTimeMillis();
		ActiveXComponent app = null;
		Dispatch doc = null;
		try {
			app = new ActiveXComponent("Word.Application");
			app.setProperty("Visible", new Variant(false));
			Dispatch docs = app.getProperty("Documents").toDispatch();
			// doc = Dispatch.call(docs, "Open" , sourceFile).toDispatch();
			doc = Dispatch.invoke(
					docs,
					"Open",
					Dispatch.Method,
					new Object[] { sfileName, new Variant(false),
							new Variant(true) }, new int[1]).toDispatch();
			System.out.println("打开文档..." + sfileName);
			System.out.println("转换文档到PDF..." + toFileName);
//			File tofile = new File(toFileName);
//			if (tofile.exists()) {
//				tofile.delete();
//			}
			// Dispatch.call(doc, "SaveAs", destFile, 17);
			Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
					toFileName, new Variant(17) }, new int[1]);
			long end = System.currentTimeMillis();
			System.out.println("转换完成..用时" + (end - start) + "ms.");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("========Error:文档转换失败" + e.getMessage());
		} finally {
			Dispatch.call(doc, "Close", false);
			System.out.println("关闭文档");
			if (app != null)
				app.invoke("Quit", new Variant[] {});
		}
		ComThread.Release();
	}

	public static void main(String[] args) {
		WordToPdf d = new WordToPdf();
		d.wordToPDF("E:/testHtml/1.docx", "E:/abc/2.pdf");
	}
}


运行环境:window64位,office2010;jacob-1.17-M2-x64.dll也放在了jre/bin目录下,自己做的测试没问题,能正常转换成功,可加到项目中来,一直报错,经排查发现:

在执行

Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {toFileName, new Variant(17) }, new int[1]);

这句之前,pdf就已经生成了,但是生成是有问题的pdf文件,当再次执行

Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {toFileName, new Variant(17) }, new int[1]);

这句话时,由于之前的文件有问题,所有word内容是写不进去的,故在此句代码执行前进行了判断:

File tofile = new File(toFileName);
	if (tofile.exists()) {
		tofile.delete();
	}

由于自己之前不清楚将这句代码注释了,所有引起的报错。

猜你喜欢

转载自blog.csdn.net/woweipingzui/article/details/51052766
今日推荐