ftl 生成pdf 可列印、可下載
阿新 • • 發佈:2018-12-31
/**
* 生成pdf可以下載、列印
* @param request
* @param response
* @param pdfName 配置檔名稱(html和pdf兩個頁面)
* @param root 需要傳到頁面 的引數
* @throws DocumentException
* @throws IOException
* @throws TemplateException
*/
public static void pdf(HttpServletRequest request,HttpServletResponse response,String pdfName,Map<String, Object> root) throws DocumentException, IOException, TemplateException
{
String basePath = request.getSession().getServletContext()
.getRealPath("/");
/* 建立配置 */
@SuppressWarnings("deprecation")
Configuration cfg = new Configuration();
/* 指定模板存放的路徑 */
cfg.setDirectoryForTemplateLoading(new File(basePath + "/WEB-INF/ftl/pdf"));
cfg.setDefaultEncoding("UTF-8");
/* 從上面指定的模板目錄中載入對應的模板檔案 */
Template temp = cfg.getTemplate(pdfName+".ftl");
/* 將生成的內容寫入hello .html中 */
String file1 = basePath + "/WEB-INF/ftl/pdf/"+pdfName+".html";
File file = new File(file1);
if (!file.exists())
file.createNewFile();
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file), "utf-8"));
temp.process(root, out);
out.flush();
String url = new File(file1).toURI().toURL().toString();
OutputStream os = response.getOutputStream();
ITextRenderer renderer = new ITextRenderer();
// PDFEncryption pdfEncryption = new
// PDFEncryption(null,null,PdfWriter.ALLOW_PRINTING);
// renderer.setPDFEncryption(pdfEncryption); //只有列印許可權的
renderer.setDocument(url);
// 解決中文問題
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont(basePath + "/WEB-INF/classes/simsun.ttf",
BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
fontResolver.addFont(basePath + "/WEB-INF/classes/ARIALUNI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
renderer.layout();
renderer.createPDF(os);
os.close();
}
頁面、ftl共用
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>列印/匯出驗收單</title>
<style type="text/css">
body {
margin-left: 45px;
margin-right: 45px;
font-family: Arial Unicode MS;
font-size: 10px;
}
table {
margin: auto;
width: 100%;
border-collapse: collapse;
border: 1px solid #444444;
}
th,td {
border: 1px solid #444444;
font-size: 10px;
margin-left: 5px;
}
td {
width: 150px;
}
@page {
size: 12in 9in;
margin: 0.25in;
-fs-flow-top: "header";
-fs-flow-left: "left";
-fs-flow-right: "right";
}
</style>
</head>
<body>
<div>
<div>
<div>
<div style="text-align:center;margin:0 auto 20px">
<span style="font-size: 20px;">${receiptName}</span>
</div>
<div style="font-size: 12px;">編碼:${receiptId}</div>
<table >
<tr>
<th>物資編碼</th>
<th>物資名稱</th>
<th>物資型號</th>
<th>品牌</th>
<th>技術引數</th>
<th>驗收部門名稱</th>
<th>驗收人</th>
<th>驗收時間</th>
<th>訂購數量</th>
<th>供貨數量</th>
<th>合格數量</th>
<th>退回數量</th>
</tr>
${rlShow}
</table>
</div>
</div>
</div>
</body>
</html>
主要用的jar:
freemarker
itext