1、應用技術java
Java模板引擎:FreeMarkerapp
Xml文檔處理:SAXReaderdom
Pio:pio技術 編輯器
jacob:文檔處理 Jar文件版本和dll版本要一致ui
2、實現思路編碼
一、利用Jacob 將Word生成 (xml)模板文件。spa
二、用步驟一取得取得圖片(印章)Base64編碼字符.net
三、將XMl文件中的(印章)字符替換成(印章)Base64編碼字符並保存成ftl模板文件。code
四、利用freemarder 模板文件生成word(也能夠加載相關動態數據)xml
3、相關代碼
public static void main(String[] args) throws IOException { Configuration cfg = FreeMarkers.buildConfiguration("classpath:/"); Map <String,Object> modle=new HashMap(); //modle.put("name", "長"); //modle.put("head",getImgStr("yingzhang.jpg") ); modle.put("header","y4Au+aaa6655gKwa6655poLwK655pprrr")//公章圖片Based64編碼 Template template = cfg.getTemplate("\\freemarker\\demo.ftl"); String result2 = FreeMarkers.renderTemplate(template, modle); System.out.println(result2); FileUtils.writeToFile("path\\demo.doc", result2, false); }
import org.dom4j.DocumentException; import com.jacob.activeX.ActiveXComponent; import com.jacob.com.Dispatch; import com.jacob.com.Variant; public class Word2Xml { /** * * @Description: * @param filePath word目錄 * @param xmlFilePath 生成xml存放路徑 * @author Administrator */ public static void wordToXml(String filePath,String xmlFilePath){ try { ActiveXComponent app = new ActiveXComponent( "Word.Application"); //啓動word app.setProperty("Visible", new Variant(false)); //爲false時設置word不可見,爲true時是可見要否則看不到Word打打開文件的過程 Dispatch docs = app.getProperty("Documents").toDispatch(); //打開編輯器 Dispatch doc = Dispatch.invoke(docs, "Open", Dispatch.Method, new Object[] {filePath, new Variant(false), new Variant(true)} , new int[1]).toDispatch(); //打開word文檔 Dispatch.call(doc, "SaveAs", xmlFilePath, 11);//xml文件格式宏11 Dispatch.call(doc, "Close", false); app.invoke("Quit",0); System.out.println("---------word轉換完成--------"); }catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws DocumentException { wordToXml("path\\範例.xml"); GetXml.stringToMxl(GetXml.xmlToString()); } }
import java.io.File; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class GetXml { public static String xmlToString() throws DocumentException { //建立SAXReader對象 SAXReader reader = new SAXReader(); //讀取文件 轉換成Document Document document = reader.read(new File("path\\範例.xml")); //document轉換爲String字符串 String documentStr = document.asXML(); System.out.println("xml to String 字符串:" + documentStr); System.out.println("替換掉蓋章"); String re=StringUtils.replace(documentStr, "章)", "${header}"); return re; } public static void stringToMxl(String result){ FileUtils.writeToFile("path\\demo.ftl", result, false); } }
4、參考資料
QC班長:
http://blog.csdn.net/qq_35624642/article/details/52209856
http://blog.csdn.net/ty497122758/article/details/8883460