jar:java
<dependency>
<groupId>com.jacob</groupId>
<artifactId>jacob</artifactId>
<version>1.10</version>
</dependency>tomcat
在tomcat上使用時要在tomcat使用的jdk的jdk/jre/bin目錄下放置配套的jacob.dll文件app
import java.io.File;ui import com.jacob.activeX.ActiveXComponent;spa import com.jacob.com.ComThread;orm import com.jacob.com.Dispatch;ci
public class WordtoPdfUtil {文檔 static final int wdDoNotSaveChanges = 0;// 不保存待定的更改。get static final int wdFormatPDF = 17;// PDF 格式it
/** * word轉pdf * @param wordSrc word路徑 * @param pdfSrc 另存爲pdf後的路徑 */ public static void wordToPdf(String wordSrc,String pdfSrc){ long start = System.currentTimeMillis(); ActiveXComponent app = null; Dispatch docs=null; try { System.runFinalizersOnExit(true); app = new ActiveXComponent("Word.Application"); app.setProperty("Visible", false);
docs = app.getProperty("Documents").toDispatch(); System.out.println("打開文檔" + wordSrc); Dispatch doc = Dispatch.call(docs,// "Open", // wordSrc,// FileName false,// ConfirmConversions true // ReadOnly ).toDispatch();
System.out.println("轉換文檔到PDF" + pdfSrc); File tofile = new File(pdfSrc); //若是輸出目標文件夾不存在,則建立 if (!tofile.getParentFile().exists()){ tofile.getParentFile().mkdirs(); } Dispatch.call(doc,// "SaveAs", // pdfSrc, // FileName wdFormatPDF);
Dispatch.call(doc, "Close", false); long end = System.currentTimeMillis();
System.out.println("轉換完成..用時:" + (end - start) + "ms."); } catch (Exception e) { e.printStackTrace(); System.out.println("========Error:文檔轉換失敗:" + e.getMessage()); } finally { if (app != null){ app.invoke("Quit", wdDoNotSaveChanges); } if(docs != null){ ComThread.Release(); ComThread.RemoveObject(docs); } } } public static void main(String[] args) { WordtoPdfUtil.wordToPdf("C:\\Users\\Administrator\\Desktop\\qcs.docx","C:\\Users\\Administrator\\Desktop\\qcs.pdf"); } } |