Jacob模板替換生成word文件、word合併、word轉pdf文件

Jacob模板替換生成word文件、word合併、word轉pdf文件java

package com.sdp.utils;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;

public class JacobWordUtil {
	
	private static ActiveXComponent word = null;
	private static Dispatch document = null;
	private static Dispatch wordDoc = null;

	/**
	 * WORD組件初始化
	 */
	public static void wordInit() {
		System.out.println("ComThread.wordInit()");
		ComThread.InitMTA(true);
		word = new ActiveXComponent("Word.Application");
		Dispatch.put(word, "Visible", new Variant(false));
		word.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
		document = word.getProperty("Documents").toDispatch();
		System.out.println("ComThread.wordInitEND()");
	}
	
	/**
	 * 模板替換生成word文件
	 * @param templateName  模板名稱(不帶後綴)
	 * @param params  內容替換參數
	 * @param ispdf   是否轉爲PDF
	 * @return
	 * @throws Exception
	 */
	public static String executeWord(String templateName, List<?> params, boolean ispdf) throws Exception {
		//初始化word
		wordInit();
		//模板文件路徑
		String tempPath = getTemplate(templateName);
		//生產文件路徑
		String savePath = getFileStore(templateName);
		//替換生成word
		replace(params, tempPath, savePath, ispdf);
		//關閉資源
		release();
		
		System.out.println("模板文件路徑:" + tempPath);
		System.out.println("生成文件路徑:" + savePath);
		return savePath;
	}
	
	/**
	 * 模板替換生成word文件
	 * @param filePath  待替換文件路徑
	 * @param params  內容替換參數
	 * @param ispdf   是否轉爲PDF
	 * @return
	 * @throws Exception
	 */
	public static String executeWordPath(String filePath, List<?> params, boolean ispdf) throws Exception {
		//初始化word
		wordInit();
		//生產文件路徑
		int index = filePath.lastIndexOf("/");
		String savePath = filePath.substring(0, index) + "/word/" + filePath.substring(index, filePath.length());
		//替換生成word
		replace(params, filePath, savePath, ispdf);
		//關閉資源
		release();
		
		System.out.println("文件路徑:" + filePath);
		System.out.println("生成文件路徑:" + savePath);
		return savePath;
	}
	
	/**
	 * 獲取文件模板路徑
	 * 
	 * @return
	 * @throws IOException
	 */
	private static String getTemplate(String templateName) throws Exception {
		String path = JacobWordUtil.class.getClassLoader().getResource("word-template").getPath();
		String templatePath = path + templateName + ".doc";
		return templatePath.substring(1, templatePath.length());
	}
	
	/**
	 * 獲取文件存儲路徑
	 * 
	 * @return
	 * @throws IOException
	 */
	private static String getFileStore(String templateName) throws IOException {
		Prop propFile = PropKit.use("bs-fileserver.properties");
		String fileRoot = propFile.get("bs.fileserver.local.root");
		String fileStore = propFile.get("bs.fileserver.store");
		//生成文件名稱
		String name = templateName + "_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		return fileRoot + fileStore + "/" + templateName + "/" + name + ".doc";
	}
	
	/**
	 * 替換word中佔位符
	 */
	@SuppressWarnings("unchecked")
	private static void replace(List<?> params, String tempPath, String savePath, boolean ispdf) {
		try {
			// 不打開WORD複製
			wordDoc = Dispatch.invoke(document,"Open",Dispatch.Method,
				new Object[] { tempPath, new Variant(false),new Variant(true) }, new int[1]).toDispatch();

			// 查找替換內容
			Dispatch selection = word.getProperty("Selection").toDispatch();
			for (int i = 0; i < params.size(); i++) {
				String findStr = "{" + (i + 1) + "}";
				if (find(selection, findStr)) {
					if(params.get(i) instanceof Map){
						Map<String,Object> infoMap = (Map<String,Object>)params.get(i);
						if(infoMap.get("img") != null){
							String imagePath = infoMap.get("Path").toString();
							Dispatch image = Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(), 
									"AddPicture", imagePath).toDispatch();
							//處理圖片樣式
							setImgStyle(image, infoMap);
							Dispatch.call(selection, "MoveRight");
						}else {
							//處理文字樣式
							setFont(selection, infoMap);
							Dispatch.put(selection, "Text", infoMap.get("Text"));
						}
					}else if(params.get(i) instanceof String){
						Dispatch.put(selection, "Text", params.get(i));
					}
					
					// 刪除空行
					if ("delete".equals(params.get(i))) {
						Dispatch.put(selection, "Text", "");
						Dispatch.call(selection, "Delete");
					} else {
						// 查詢右移
						Dispatch.call(selection, "MoveRight");
					}
				}
			}
			save(savePath, ispdf);// 保存
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 文件保存或另存爲
	 * 
	 * @param savePath 保存或另存爲路徑
	 */
	private static void save(String savePath, boolean ispdf) {
		int index = savePath.lastIndexOf("/");
		if(!new File(savePath.substring(0, index)).exists()){
			new File(savePath.substring(0, index)).mkdirs();
		}
		if(ispdf){
			Dispatch.put(wordDoc, "ShowRevisions", new Variant(false));
			Dispatch.call((Dispatch) Dispatch.call(word, "WordBasic").getDispatch(),"FileSaveAs", savePath);
			Dispatch.invoke(wordDoc, "SaveAs", Dispatch.Method, 
				new Object[] {savePath.replace(".doc", ".pdf"), new Variant(17)}, new int[1]);
		}else{
			Dispatch.call((Dispatch) Dispatch.call(word, "WordBasic").getDispatch(),"FileSaveAs", savePath);
		}
	}

	private static boolean find(Dispatch selection, String toFindText) {
		// 從selection所在位置開始查詢
		Dispatch find = Dispatch.call(selection, "Find").toDispatch();
		// 設置要查找的內容
		Dispatch.put(find, "Text", toFindText);
		// 向前查找
		Dispatch.put(find, "Forward", "True");
		// 設置格式
		Dispatch.put(find, "format", "True");
		// 大小寫匹配
		Dispatch.put(find, "MatchCase", "True");
		// 全字匹配
		Dispatch.put(find, "MatchWholeWord", "True");
		// 查找並選中
		return Dispatch.call(find, "Execute").getBoolean();
	}
	
	/** 
     * 設置當前選定內容的字體 
     * 
     * @param image 文字對象
	 * @param param 文字參數
     */  
	private static void setFont(Dispatch selection, Map<String,Object> param) { 
		Dispatch font = Dispatch.get(selection, "Font").toDispatch();
        //設置字體
		if(param.get("Name") != null){
			Dispatch.put(font, "Name", new Variant(param.get("Name")));
		}
        //設置粗體
        Dispatch.put(font, "Bold", new Variant(param.get("Bold")!=null?param.get("Bold"):false)); 
        //設置斜體
        Dispatch.put(font, "Italic", new Variant(param.get("Italic")!=null?param.get("Bold"):false)); 
        //設置下劃線
        Dispatch.put(font, "Underline", new Variant(param.get("Underline")!=null?param.get("Bold"):false));
        //設置字體顏色
        if(param.get("Color") != null){
        	Dispatch.put(font, "Color", Integer.valueOf(param.get("Color").toString(),16));
        }
        //設置字體大小
        if(param.get("Size") != null){
        	Dispatch.put(font, "Size", param.get("Size"));
        }
    }
	
	/**
	 * 設置圖片樣式
	 * 
	 * @param image 圖片對象
	 * @param param 圖片參數
	 * 
	 * 環繞格式(0-7)
	 * wdWrapSquare     0 使文字環繞形狀。行在形狀的另外一側延續。
	 * wdWrapTight      1 使文字緊密地環繞形狀。
	 * wdWrapThrough    2 使文字環繞形狀。
	 * wdWrapNone       3 將形狀放在文字前面。
	 * wdWrapTopBottom  4 將文字放在形狀的上方和下方。
	 * wdWrapBehind     5 將形狀放在文字後面。
	 * wdWrapFront      6 將形狀放在文字前面。
	 * wdWrapInline     7 將形狀嵌入到文字中。
	 */
	private static void setImgStyle(Dispatch image, Map<String,Object> param){
		//選中圖片
		Dispatch.call(image, "Select");
		//圖片的寬度
		if(param.get("Width") != null){
			Dispatch.put(image, "Width", new Variant(param.get("Width")));
		}
		//圖片的高度
		if(param.get("Height") != null){
			Dispatch.put(image, "Height", new Variant(param.get("Height"))); 
		}
		//取得圖片區域
		Dispatch ShapeRange = Dispatch.call(image, "ConvertToShape").toDispatch();
		//取得圖片的格式對象
		Dispatch WrapFormat = Dispatch.get(ShapeRange, "WrapFormat").toDispatch();
		//設置環繞格式
		Dispatch.put(WrapFormat, "Type", param.get("Type")!=null?param.get("Type"):6);
	}
	
	/**
	 * 關閉全部資源
	 */
	private static void release() {
		// 始終釋放資源
		if(word != null){
			word.invoke("Quit", new Variant[] {});
		}
		ComThread.Release();
	}
	
	/**
	 * word文件合併
	 * @param fileList 合併文件集合
	 * @param savepaths 合併後文件保存路徑
	 */
	public static void uniteWord(List<String> fileList, String savepaths) throws Exception {  
        if (fileList.size() == 0 || fileList == null) {  
            return;  
        }  
        //打開word  
        ActiveXComponent app = new ActiveXComponent("Word.Application");//啓動word  
        // 設置word不可見
        app.setProperty("Visible", new Variant(false));  
        //得到documents對象  
        Object docs = app.getProperty("Documents").toDispatch();
        //打開第一個文件  
        Object doc = Dispatch.invoke((Dispatch) docs, "Open", Dispatch.Method,  
            new Object[] { (String) fileList.get(0), new Variant(false), new Variant(true) },  
            new int[3]).toDispatch();  
        
        //追加文件  
        for (int i = 1; i < fileList.size(); i++) {
        	Dispatch selection = Dispatch.get(app, "Selection").toDispatch();
        	// 到文檔末尾
        	Dispatch.call(selection, "EndKey" , "6" );
            //插入分頁符
            Dispatch.call(app, "Run", new Variant("InsertBreakWdSectionBreakNextPage"));
            
            Dispatch.invoke(app.getProperty("Selection").toDispatch(),  
                "insertFile", Dispatch.Method, new Object[] {  
                (String) fileList.get(i), "",  
                new Variant(false), new Variant(false),  
                new Variant(false) }, new int[3]);  
        }  
        //保存新的word文件  
        Dispatch.invoke((Dispatch) doc, "SaveAs", Dispatch.Method,  
            new Object[] { savepaths, new Variant(1) }, new int[3]);  
        Variant f = new Variant(false);  
        Dispatch.call((Dispatch) doc, "Close", f);  
    }
	
	/**
	 * word文件轉PDF文件
	 * @param sfileName   待轉word文件
	 * @param toFileName  pdf保存路徑
	 */
	public static void wordToPDF(String sfileName,String toFileName) throws Exception {  
		//初始化
		wordInit();
		//不打開WORD複製
    	wordDoc = Dispatch.invoke(document,"Open",Dispatch.Method,new Object[] {                    
           sfileName, new Variant(false),new Variant(true) }, new int[1]).toDispatch();             
        File tofile = new File(toFileName);      
        if (tofile.exists()) {      
            tofile.delete();      
        } 
        Dispatch.call(word, "Run", new Variant("finalStatewordToPdf"));
        Dispatch.invoke(wordDoc, "SaveAs", Dispatch.Method, new Object[] {               
            toFileName, new Variant(17) }, new int[1]);   
        //關閉資源
        release();
    }

    public static void main(String[] args) {
                //此處僅爲調用說明與參數解釋
		//圖片、帶格式字符串參數如不須要的不傳便可
		try {
			/**圖片替換參數**/
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("img", true);
			map.put("Width", 30);
			map.put("Height", 40);
			map.put("Path", "D:\\wyh.png");
			/**帶格式字符替換參數**/
			Map<String,Object> mapF = new HashMap<String,Object>();
			mapF.put("Text", "地址:張川縣竹園鎮");
			mapF.put("Name", "華文隸書");  //字體
			mapF.put("Bold", true);        //粗體
			mapF.put("Italic", true);      //斜體
			mapF.put("Underline", true);  //下劃線
			mapF.put("Color", "FFFFFF");   //顏色(例如白色:FFFFFF)
			mapF.put("Size", 26);           //字體大小
			/**無格式字符替換參數**/
			List<Object> params = Lists.newArrayList();
			params.add("李四");
			params.add("610321000000111111");
			params.add(map);
			params.add(mapF);
			
			JacobWordUtil.executeWord("test", params, true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

jacob相關配置文件、word下載:app

連接:https://pan.baidu.com/s/1miR81Qg      密碼:c3jw字體

相關文章
相關標籤/搜索