1 先找到word模板,用${},替換變量,保存,然后另存為xml,最后把xml后綴改成ftl。
如下圖:
word 模板文件
ftl模板文件如下:
2 代碼生成
下面函數(shù)將ftl填充數(shù)據(jù),并生成word和pdf
/**
*
* @param dataMap 模板需要填充的數(shù)據(jù)
* @param templateName 模板名稱
* @param format 生成的文件格式
* @return 生成的文件路徑
*/
public static String ftl2word2pdf(Map<String, Object> dataMap, String templateName, int format) {
if (!getLicense()) { // 驗證License 若不驗證則轉(zhuǎn)化出的pdf文檔會有水印產(chǎn)生
return null;
}
FileOutputStream os = null;
try {
/**
* 模板以及生成word pdf 存放路徑
*/
String path="C:\\Users\\Administrator\\Desktop\\asposeTest\\";
/**
* 先根據(jù)ftl模板生成word
*/
File directory = new File(path);
String absolutePath = directory.getAbsolutePath();
Configuration configuration = new Configuration(new Version("2.3.0"));
configuration.setDefaultEncoding("utf-8");
configuration.setDirectoryForTemplateLoading(new File(absolutePath));
//.ftl配置文件所在路徑
Template template = configuration.getTemplate(templateName, "utf-8");
/**
* 生成臨時word 文件
*/
//輸出文檔路徑及名稱
//臨時文件的文件名
String tempFileName= UUID.randomUUID().toString();
String tempWordName=path+File.separator+ tempFileName+".docx";
File outFile = new File(tempWordName);
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),
"utf-8"), 10240);
template.process(dataMap, out);
out.close();
System.out.println("Execute Word:"+tempWordName);
String tempPdfName=path+File.separator+tempFileName+".pdf";
File file = new File(tempPdfName); // 新建一個空白pdf文檔
os = new FileOutputStream(file);
Document doc = new Document(tempWordName);
doc.save(os,format);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
// EPUB, XPS, SWF 相互轉(zhuǎn)換
System.out.println("Execute Pdf:"+tempPdfName);
//Files.deleteIfExists(Paths.get(tempWordName));//刪除臨時文件
return tempPdfName;
} catch (Exception e) {
e.printStackTrace();
return null;
}finally {
if (os != null) {
try {
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3 測試主程序文章來源:http://www.zghlxwxcb.cn/news/detail-641880.html
public static void main(String[] args) {
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("name", "斯蒂芬·庫里");
dataMap.put("age", "33");
dataMap.put("team", "金州勇士隊");
dataMap.put("city", "奧克蘭");
dataMap.put("location", "控球后衛(wèi)");
dataMap.put("no", "30");
dataMap.put("info", "投籃準(zhǔn)、出手速度快、善于搶斷與投三分球");
ftl2word2pdf(dataMap,"playerInfo.ftl",SaveFormat.PDF);
System.out.println("success......");
}
4 結(jié)果:
pdf文件
word文件
還可以生成圖片:文章來源地址http://www.zghlxwxcb.cn/news/detail-641880.html
到了這里,關(guān)于aspose 使用ftl模板生成word和pdf的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!