java將word檔案轉為pdf

來源:互聯網
上載者:User

標籤:word   prope   cat   覆蓋   main   文檔   port   exist   pen   

 

import java.io.File;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;

public class Word2Pdf
{
public static void main(String args[])
{
ActiveXComponent app = null;
String wordFile = "C:/xxxxx.doc";
String pdfFile = "C:/xxxxx.pdf";
System.out.println("開始轉換...");
long start = System.currentTimeMillis();
try
{
// 開啟word
app = new ActiveXComponent("Word.Application");
// app.setProperty("Visible", false);
// 獲得word中所有開啟的文檔
Dispatch documents = app.getProperty("Documents").toDispatch();
System.out.println("開啟檔案: " + wordFile);
// 開啟文檔
Dispatch document = Dispatch.call(documents, "Open", wordFile, false, true).toDispatch();
// 如果檔案存在的話,不會覆蓋,會直接報錯,所以我們需要判斷檔案是否存在
File target = new File(pdfFile);
if (target.exists())
{
target.delete();
}
System.out.println("另存新檔: " + pdfFile);
// 另存新檔,將文檔報錯為pdf,其中word儲存為pdf的格式宏的值是17
Dispatch.call(document, "SaveAs", pdfFile, 17);
// 關閉文檔
Dispatch.call(document, "Close", false);
// 結束時間
long end = System.currentTimeMillis();
System.out.println("轉換成功,用時:" + (end - start) + "ms");
}
catch (Exception e)
{
System.out.println("轉換失敗" + e.getMessage());
}
finally
{
// 關閉office
app.invoke("Quit", 0);
}
}
}

 

涉及jar包 jacob.jar 可在 http://sqdownb.onlinedown.net/down/74195_20170622162225.zip 下載

java將word檔案轉為pdf

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.