使用jacob將word轉成PDF

整體思路參考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

810

htm

11

Xml

1216

Docx

13

Docm

14

Dotx

15

Dotm

17

Pdf

 

我使用的是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);
		}		
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章