一、应用技术
Java模板引擎:FreeMarker
Xml文档处理:SAXReader
Pio:pio技术
jacob:文档处理 Jar文件版本和dll版本要一致
二、实现思路
1、利用Jacob 将Word生成 (xml)模板文件。
2、用步骤一取得取得图片(印章)Base64编码字符
3、将XMl文件中的(印章)字符替换成(印章)Base64编码字符并保存成ftl模板文件。
4、利用freemarder 模板文件生成word(也可以加载相关动态数据)
三、相关代码
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);
}
}
四、参考资料
QC班长:
http://blog.youkuaiyun.com/qq_35624642/article/details/52209856
http://blog.youkuaiyun.com/ty497122758/article/details/8883460