java word 转 pdf

时间:2022-02-21 12:24:38

这里使用jacob将word转pdf,使用的是jacob.jar

import java.io.File;

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

public class WordToPDF {

    /**
     * 使用jacob将word转pdf
     *
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String source1 = "c:\\peng2.doc";
        String target1 = "d:\\test1.pdf";
        word2pdf(source1, target1);
    }

    public static void word2pdf(String source, String target) {
        System.out.println("Word转PDF开始启动...");
        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        try {
            app = new ActiveXComponent("Word.Application");  
            app.setProperty("Visible", false);  
            Dispatch docs = app.getProperty("Documents").toDispatch();  
            System.out.println("打开文档:" + source);  
            Dispatch doc = Dispatch.call(docs, "Open", source, false, true).toDispatch();  
            System.out.println("转换文档到PDF:" + target);  
            File tofile = new File(target);  
            if (tofile.exists()) {  
                tofile.delete();  
            }  
            Dispatch.call(doc, "SaveAs", target,17);  
            Dispatch.call(doc, "Close", false);  
            long end = System.currentTimeMillis();  
            System.out.println("转换完成,用时:" + (end - start) + "ms");  
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("Word转PDF出错:" + e.getMessage());
            
        }finally{
            
        }
    }
}