Java自動生成帶圖片、富文本、表格等的word文檔
- 使用技術 freemark+jsoup 生成mht格式的偽word文檔,已經應用項目中,確實是可行的,無論是富文本中是圖片還是表格,都能在word中展現出來
使用jsoup解析富文本框,將其中的圖片進行Base64位轉碼,
使用freemark替換模板的占位符,將變量以及圖片資源放入模板中在輸出文件
- maven地址
<!--freemarker-->
<!--https://mvnrepository.com/artifact/org.freemarker/freemarker-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<!--JavaHTMLParser-->
<!--https://mvnrepository.com/artifact/org.jsoup/jsoup-->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.2</version>
</dependency>
- 制作word的freemark模板
- 先將wrod的格式內容定義好,如果需要插入參數的地方以${xxx}為表示,例:${product}
模板例子:
2. 將模板另存為mht格式的文件,打開該文件檢查每個變量(${product})是否完整,有可能在${}中出現其他代碼,需要刪除。
3. 將mht文件變更文件類型,改成ftl為結尾的文件,引入到項目中
4. 修改ftl模板文件,在文件中加上圖片資源占位符${imagesBase64String},${imagesXmlHrefString}
具體位置如下圖所示:

5. ftl文件中由幾個關鍵配置需要引入到代碼中:
docSrcParent = word.files
docSrcLocationPrex = file:///C:/268D4AA4
nextPartId = 01D2C8DD.BC13AF60
上面三個參數,在模板文件中可以找到,需要進行配置,如果配置錯誤,圖片文件將不會顯示
下面這三個參數固定,切換模板也不會改變
shapeidPrex = _x56fe__x7247__x0020
typeid = #_x0000_t75
spidPrex = _x0000_i
6. 模板引入之后進行代碼編輯
源碼地址為:https://gitee.com/zhengweishan/export_word_plugin
下載源碼后需要進行調整下內容:
- 錄入步驟5中的6個參數
- 修改freemark獲取模板方式
下面這種方式能獲取模板,但是在項目打包之后無法獲取jar包內的文件
Configuration configuration=newConfiguration(Configuration.getVersion());
configuration.setDefaultEncoding(StandardCharsets.UTF_8.toString());
configuration.setDirectoryForTemplateLoading(newFile(templatePath));
Template template=configuration.getTemplate("xxx.ftl");
通過流的形式直接創建模板對象
Configuration configuration=newConfiguration(Configuration.getVersion());
configuration.setDefaultEncoding(StandardCharsets.UTF_8.toString());
configuration.setDirectoryForTemplateLoading(newFile(templatePath));
InputStream inputStream=newFileInputStream(newFile(templatePath+"/"+templateName));
InputStreamReader inputStreamReader=newInputStreamReader(inputStream,StandardCharsets.UTF_8);
Template template=newTemplate(templateName,inputStreamReader,configuration);
