HTML 模板+freemarker渲染 生成PDF(一)
阿新 • • 發佈:2019-01-01
最近專案中要把相關資料匯出為PDF檔案,總結下自己寫這個功能遇到的種種問題
先給出個大概的框架
package com.xsm;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import com.sectechio.fintech.common.utils.PDFUtil;
public class PDFtest {
@Test
public void createPDF(){
String path = "D:/test";
String name = "test.html";
String content = "'\r \n<html>\r\n\r\n<head>\r\n<meta http-equiv=Content-Type content=\"text/html; charset=gb2312\"></meta>\r\n<meta name=Generator content=\"Microsoft Word 15 (filtered)\"></meta>\r\n\r\n\r\n</head>\r\n\r\n<body style=\'text-justify-trim:punctuation\'>\r\n\r\n${ bankName}年利率是:${interest}%\r\n\r\n</body>\r\n\r\n</html>\r\n'";
Map<String, Object> paraMap = new HashMap<String, Object>();
paraMap.put("bankName", "小人國銀行");
paraMap.put("interest", 36);
PDFUtil pdfUtil = new PDFUtil(path,name);
pdfUtil.createdHtmlTemplate(content);
try {
String uploadfile = pdfUtil.fillTemplate(paraMap);
System.out.println(uploadfile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
說明:
1、把需要用的HTML模板寫好後,可以存到資料庫裡(我用的是longtext型別儲存),這裡作為演示把一個模板從資料庫裡匯出,直接寫死在程式碼裡。有一些樣式,freemark不支援,這個自己可以摸索。我用的模板多是表格,是先用Word寫好,然後儲存為html檔案,在瀏覽器中開啟後,右鍵檢視原始碼,再稍微改動下,就有了HTML模板。
2、引數的處理,以後篇章再細說,這裡只做最簡單的演示。在模板中引數用 ${} 這個來顯示。
這個是編寫的HTML模板(程式碼裡用的,是資料庫匯出的,有換行什麼的,不然後報錯)
這個是生成的PDF檔案
所用的工具類如下:
public class PDFUtil {
private String tempFilePath;
private String tempFileName;
public PDFUtil() {}
public PDFUtil(String tempFilePath, String tempFileName) {
this.tempFilePath=tempFilePath;
this.tempFileName=tempFileName;
}
public String getTempFilePath() {
return tempFilePath;
}
public void setTempFilePath(String tempFilePath) {
this.tempFilePath = tempFilePath;
}
public String getTempFileName() {
return tempFileName;
}
public void setTempFileName(String tempFileName) {
this.tempFileName = tempFileName;
}
public void test() throws Exception {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("loanId", "LO123456"); //訂單ID
paramMap.put("realName", "張三"); //訂單ID
paramMap.put("cardNo", "110001451121111"); //訂單ID
paramMap.put("name", "張三"); //訂單ID
paramMap.put("loanAmount", "56.00"); //訂單ID
paramMap.put("loanAmountCharacter", "五十六元整"); //訂單ID
paramMap.put("timeLimit", "3"); //訂單ID
paramMap.put("annualRate", "0.88"); //訂單ID
paramMap.put("bankName", "建設銀行"); //訂單ID
paramMap.put("bankNo", "622655555555"); //訂單ID
paramMap.put("order_id", "1"); //訂單ID
fillTemplate(paramMap) ;
}
/**
* 填充模板
* @param paramMap
* @throws Exception
*/
public String fillTemplate(Map<String, Object> paramMap) throws Exception {
File modelFile = new File(tempFilePath);
if(!modelFile.exists()) {
modelFile.mkdirs();
}
Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
configuration.setDirectoryForTemplateLoading(modelFile);
configuration.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_23));
configuration.setDefaultEncoding("UTF-8"); //這個一定要設定,不然在生成的頁面中 會亂碼
//獲取或建立一個模版。
Template template = configuration.getTemplate(tempFileName);
StringWriter stringWriter = new StringWriter();
BufferedWriter writer = new BufferedWriter(stringWriter);
template.process(paramMap, writer);
String htmlStr = stringWriter.toString();
writer.flush();
writer.close();
String tmpPath = tempFilePath + "/temp";
File tmepFilePath = new File(tmpPath);
if (!tmepFilePath.exists()) {
tmepFilePath.mkdirs();
}
String tmpFileName =System.currentTimeMillis()+".pdf";
String outputFile = tmpPath + File.separatorChar + tmpFileName;
FileOutputStream outFile = new FileOutputStream(outputFile);
createPDFFile(htmlStr, outFile);
return outputFile;
}
/**
* 根據HTML字串建立PDF檔案
* @param htmlStr
* @param outputFile
* @throws Exception
*/
private void createPDFFile(String htmlStr,OutputStream os) throws Exception{
ByteArrayInputStream bais = new ByteArrayInputStream(htmlStr.getBytes("UTF-8"));
// step 1
Document document = new Document();
try {
// step 2
PdfWriter writer = PdfWriter.getInstance(document, os);
// step 3
document.open();
FontProvider provider = new FontProvider();
XMLWorkerHelper.getInstance().parseXHtml(writer, document, bais, Charset.forName("UTF-8"),provider);
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally {
try {
document.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
bais.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
*
* 字型
*
*/
private class FontProvider extends XMLWorkerFontProvider{
public Font getFont(final String fontname, final String encoding,
final boolean embedded, final float size, final int style,
final BaseColor color) {
BaseFont bf = null;
try {
bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
} catch (Exception e) {
e.printStackTrace();
}
Font font = new Font(bf, size, style, color);
font.setColor(color);
return font;
}
}
/**
* 生成html模板
* @param content
* @return
*/
public String createdHtmlTemplate(String content){
String fileName = tempFilePath + "/" + tempFileName;
try{
File file = new File(tempFilePath);
if(!file.isDirectory()) {
file.mkdir();
}
file = new File(fileName);
if(!file.isFile()) {
file.createNewFile();
}
//開啟檔案
PrintStream printStream = new PrintStream(new FileOutputStream(fileName));
//將HTML檔案內容寫入檔案中
printStream.println(content);
printStream.flush();
printStream.close();
System.out.println("生成html模板成功!");
}catch(Exception e){
e.printStackTrace();
}
return fileName;
}
}