Convert Jave Word to PDF

  Recently, I have been working on a need to convert word to pdf. I can't find a lot on the Internet. Otherwise, I rely on third-party plug-ins. Finally, I realized it through jacod, and record it.

        You need to download the Jacob.jar package and put Jacob.dll in the jre/bin directory 

package com.jieyuechina.util;

import java.io.File;

import org.apache.log4j.Logger;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.jieyuechina.test.WordTest;

public class Office2Pdf {
	static final int wdFormatPDF = 17;// PDF format  
	public static final Logger log = Logger.getLogger(Office2Pdf.class);
    public void wordToPDF(String sfileName,String toFileName){  
       log.info("Start 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" , sfileName).toDispatch();
            log.info("Open file..." + sfileName);
            log.info("Convert document to PDF..." + toFileName);    
            File tofile = new File(toFileName);    
            if (tofile.exists()) {    
                tofile.delete();    
            }    
            Dispatch.call(doc, "SaveAs",  toFileName, wdFormatPDF);    
            long end = System.currentTimeMillis();    
            log.info("Conversion completed.. Time: " + (end - start) + "ms.");
        } catch (Exception e) {    
        	log.info("========Error:word to pdf document conversion failed: " + e.getMessage());    
        } finally {
        	Dispatch.call(doc,"Close",false);
            if (app != null)    
                app.invoke("Quit", new Variant[] {});    
            }
          //Without this sentence, the winword.exe process will not be closed
           ComThread.Release();   
	}
    public static void main(String[] args) {
    	Office2Pdf d = new Office2Pdf();
    	d.wordToPDF("d:\\outFile2.doc", "d:\\222.pdf");
	}

}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327093650&siteId=291194637
Recommended