事情是這樣的,系統有這樣一個需求,有一些單子供客戶下載打印,做為憑證,而這些單子一般屬於word格式的,里面的排版非常固定,只是上面的內容不同,這就屬於word模板的范疇了,目前比較不好的操作word的組件就是aspose了,下面我來說一下它的使用方法。
word模板
主要使用了word里的域,然后選擇“郵件合並”,在“域名”處輸入你的word變量名,然后在java代碼里為這個變量賦值就可以了
添加組件引用
把組件放到resource/lib目錄下
<dependency>
<groupId>com.bdyh.common</groupId>
<artifactId>common</artifactId>
<version>0.0.1</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/aspose-words-15.8.0-jdk16.jar</systemPath>
</dependency>
代碼生成
aspose組件存在授權問題,沒有授權的會有水印出現
private static InputStream license;
private static InputStream fileInput;
public static void generateApproveForm(HttpServletResponse response,
List<CompanyLawyerEducationAddDTO> counterpartDetails) {
// 驗證License
if (!getLicense("templates/companyLawyerApprove.docx")) {
return;
}
try {
long old = System.currentTimeMillis();
Document doc = new Document(fileInput);
//主要調用aspose.words的郵件合並接口MailMerge
//3.1 填充單個文本域
String[] Flds = new String[]{"Title", "Name", "URL", "Note"}; //文本域
Object[] Vals = new Object[]{"標題", "測試", "http://test.com", word模板導出"}; //值
doc.getMailMerge().execute(Flds, Vals); //調用接口
response.setHeader("Content-Disposition", "attachment; filename=審批單.pdf");
response.setContentType("application/octet-stream;charset=UTF-8");
OutputStream output = response.getOutputStream();
doc.save(output, SaveFormat.PDF);
output.flush();
output.close();
}
public static boolean getLicense(String templateName) {
boolean result = false;
try {
license = new ClassPathResource("lib/license.xml").getInputStream();
fileInput = new ClassPathResource(templateName).getInputStream();
License aposeLic = new License();
aposeLic.setLicense(license);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
以上模板是最簡單的文本域的,如果有興趣還可以把表格域也放上去,實現列表的輸出等。