項目中最近用到這個東西,做下記錄。
如下圖,先准備好一個(office2003)word文檔當做模板。文檔中圖片、姓名、性別和生日已經使用占位符代替,生成過程中將會根據實際情況進行替換。
然后將word文檔另存為“Word XML文檔”
使用xml編輯器打開test.xml,將下圖中的BASE64字符串替換為${image},后面程序中將使用這個替換圖片。
完成后,將test.xml重命名為test.ftl。
接下來,實現代碼如下:
public class ExportDoc { private Configuration configuration; private String encoding; public ExportDoc(String encoding) { this.encoding = encoding; configuration = new Configuration(Configuration.VERSION_2_3_22); configuration.setDefaultEncoding(encoding); configuration.setClassForTemplateLoading(this.getClass(), "/com/lichmama/test/templates"); } public Template getTemplate(String name) throws Exception { return configuration.getTemplate(name); } public String getImageStr(String image) throws IOException { InputStream is = new FileInputStream(image); BASE64Encoder encoder = new BASE64Encoder(); byte[] data = new byte[is.available()]; is.read(data); is.close(); return encoder.encode(data); } public Map<String, Object> getDataMap() { Map<String, Object> dataMap = new HashMap<String, Object>(); dataMap.put("name", "lichmama"); dataMap.put("gender", "男"); dataMap.put("birthday", "19**年**月**日"); try { dataMap.put("image", getImageStr("D:\\頭像.jpg")); } catch (IOException e) { e.printStackTrace(); } return dataMap; } public void exportDoc(String doc, String name) throws Exception { Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(doc), encoding)); getTemplate(name).process(getDataMap(), writer); } public static void main(String[] args) throws Exception { ExportDoc maker = new ExportDoc("UTF-8"); maker.exportDoc("D:\\test.doc", "test.ftl"); } }
生成的文檔效果如下圖:
更新:
此方案存在種種弊端,推薦大家使用pandoc、docverter或其他如poi的方式。
// pandoc https://www.pandoc.org/ // docverter(ruby) https://www.docverter.com/