1. 程式人生 > >java+jacob實現word轉pdf(通過呼叫模板檔案)

java+jacob實現word轉pdf(通過呼叫模板檔案)

package com.repair.util.pub;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

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

public class OperationIO {
	
	static final int wdFormatPDF = 17;// PDF 格式   
	/**
	 * WORD轉換PDF
	 * @param sfileName WORD檔案存在位置
	 * @param toFileName PDF檔案存放位置
	 */ 	 
	public static void wordToPDF(String sfileName,String toFileName){    
        System.out.println("啟動Word...");      
        long start = System.currentTimeMillis();   
        ActiveXComponent app = null;  
        Dispatch doc = null;  
        try {      
        	//呼叫office word
            app = new ActiveXComponent("Word.Application");      
            app.setProperty("Visible", new Variant(false));  
            Dispatch docs = app.getProperty("Documents").toDispatch();    
            doc = Dispatch.call(docs,  "Open" , sfileName).toDispatch();  
            System.out.println("開啟文件..." + sfileName);  
            System.out.println("轉換文件到PDF..." + toFileName);      
            File tofile = new File(toFileName);      
            if (tofile.exists()) {      
                tofile.delete();      
            }      
            Dispatch.call(doc,      
                          "SaveAs",      
                          toFileName, // FileName      
                          wdFormatPDF);      
            long end = System.currentTimeMillis();      
            System.out.println("轉換完成..用時:" + (end - start) + "ms.");  
              
                
        } catch (Exception e) {      
            System.out.println("========Error:文件轉換失敗:" + e.getMessage());      
        } finally {  
            Dispatch.call(doc,"Close",false);  
            System.out.println("關閉文件");  
            if (app != null)      
                app.invoke("Quit", new Variant[] {});      
            }  
          //如果沒有這句話,winword.exe程序將不會關閉  
           ComThread.Release();     
    }  
	
	/**
     * 遞迴刪除目錄下的所有檔案及子目錄下所有檔案
     * @param dir 將要刪除的檔案目錄
     * @return boolean Returns "true" if all deletions were successful.
     *                 If a deletion fails, the method stops attempting to
     *                 delete and returns "false".
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目錄此時為空,可以刪除
        return dir.delete();
    }
	/**
     * 將圖片檔案轉化為位元組陣列字串,並對其進行Base64編碼處理
     * @param imgFilePath 圖片地址路徑
     */
    public static String GetImageStr(String imgFilePath) {// 
        byte[] data = null;
         
        // 讀取圖片位元組陣列
        try {
          InputStream in = new FileInputStream(imgFilePath);
          data = new byte[in.available()];
          in.read(data);
          in.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
         
        // 對位元組陣列Base64編碼
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);// 返回Base64編碼過的位元組陣列字串
      }
    
    
    /** 
     * 將二進位制轉換為圖片 
     *  
     * @param base64String 
     */  
    public static void base64StringToImage(String base64String,String imageoutpath) {  
        try {  
        	BASE64Decoder decoder = new sun.misc.BASE64Decoder(); 
            byte[] bytes1 = decoder.decodeBuffer(base64String);  
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);  
            BufferedImage bi1 = ImageIO.read(bais);  
            File w2 = new File(imageoutpath);// 可以是jpg,png,gif格式  
            ImageIO.write(bi1, "jpg", w2);// 不管輸出什麼格式圖片,此處不需改動  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}

二:業務類(PrintWordToPdf.java),這裡