freemarker導出PDF,簡單的
1.新建一個html文件 pdf-template.html,如圖:
2.html寫你需要導出的樣式:
這裏是示範一個簡單的:
同樣需要一個list標籤,
這裏的變量要與後臺的一致
3.工具類(我這裏只是簡單的String導出pdf,日期圖片未處理):
這裏工具類借鑑:
https://blog.csdn.net/weixin_39806100/article/details/86616041
/**
* 通過模板導出pdf文件
* @param data 數據
* @param templateFileName 模板文件名
* @throws Exception
* :SIMSUN.TTC爲宋體,可在C:\Windows\Fonts中查找
*
* 文章路徑:https://blog.csdn.net/weixin_39806100/article/details/86616041
*
*/
public static ByteArrayOutputStream createPDF(Map data, String templateFileName) throws Exception {
// 創建一個FreeMarker實例, 負責管理FreeMarker模板的Configuration實例
Configuration cfg = new Configuration();
// 指定FreeMarker模板文件的位置
cfg.setClassForTemplateLoading(ImportExcelUtil.class,Const.IMPORT_TEMPLATE_PATH);
ITextRenderer renderer = new ITextRenderer();
OutputStream out = new ByteArrayOutputStream();
try {
// 設置 css中 的字體樣式(暫時僅支持宋體和黑體) 必須,不然中文不顯示
renderer.getFontResolver().addFont("/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// 設置模板的編碼格式
cfg.setEncoding(Locale.CHINA, "UTF-8");
// 獲取模板文件
Template template = cfg.getTemplate(templateFileName, "UTF-8");
StringWriter writer = new StringWriter();
// 將數據輸出到html中
template.process(data, writer);
writer.flush();
String html = writer.toString();
// 把html代碼傳入渲染器中
renderer.setDocumentFromString(html);
// 設置模板中的圖片路徑 (這裏的images在resources目錄下) 模板中img標籤src路徑需要相對路徑加圖片名 如<img src="images/xh.jpg"/>
// String url = ImportExcelUtil.class.getClassLoader().getResource("images").toURI().toString();
// renderer.getSharedContext().setBaseURL(url);
renderer.layout();
renderer.createPDF(out, false);
renderer.finishPDF();
out.flush();
return (ByteArrayOutputStream)out;
} finally {
if(out != null){
out.close();
}
}
}
4.controller:
@RequestMapping("downloadPdf")
public void downloadPdf(HttpServletResponse response) {
ByteArrayOutputStream baos = null;
OutputStream out = null;
//查詢的數據
List list = clothingService.queryAllListNoPage();
Map map = new HashMap();
//模板中的與這裏保持一致
map.put("clothingList", list);
try {
//調用工具類
baos = ImportExcelUtil.createPDF(map, Const.IMPORT_PDF_PATH);
// 設置響應消息頭,告訴瀏覽器當前響應是一個下載文件
response.setContentType("application/x-msdownload");
// 告訴瀏覽器,當前響應數據要求用戶干預保存到文件中,以及文件名是什麼 如果文件名有中文,必須URL編碼
String fileName = URLEncoder.encode("月度報告.pdf", "UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
out = response.getOutputStream();
baos.writeTo(out);
baos.close();
} catch(Exception e){
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
這樣就可以了:結束
有一個問題
輸出的漢字識別不了
如圖:(沒有設置的)
1.必須在html中設置一個字體的樣式,
需要加一個style樣式
2.導入simsun.ttc,直接放到resources文件夾下,如圖:
結果: