HTML 模板+freemarker渲染 生成PDF(一)
標簽: html+freemark PDF
最近項目中要把相關數據導出為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;
}
}
智能推薦
iText Freemarker模板生成導出PDF及部署到Linux
1.工程結構 2.maven 3 PDFKit.java FreemarkerUtil.java DownloadServlet.java參考以下資料 http://blog.csdn.net/zxz547388910/article/details/74315277 ITEXT5.5.8轉html為pdf文檔解決linux不顯示中文問題 https://segmentfault.com/a/11...
freemarker + ItextRender 根據模板生成PDF文件
1. 制作模板 2. 獲取模板,并將所獲取的數據加載生成html文件 2. 生成PDF文件 其中由兩個地方需要注意,都是關于獲取文件路徑的問題,由于項目部署的時候是打包成jar包形式,所以在開發過程中時直接安照傳統的獲取方法沒有一點文件,但是當打包后部署,總是出錯。于是參考網上文章,先將文件讀出來到項目的臨時目錄下,然后再按正常方式加載該臨時文件; 還有一個問題至今沒有解決,就是關于生成PDF文件...
電腦空間不夠了?教你一個小秒招快速清理 Docker 占用的磁盤空間!
Docker 很占用空間,每當我們運行容器、拉取鏡像、部署應用、構建自己的鏡像時,我們的磁盤空間會被大量占用。 如果你也被這個問題所困擾,咱們就一起看一下 Docker 是如何使用磁盤空間的,以及如何回收。 docker 占用的空間可以通過下面的命令查看: TYPE 列出了docker 使用磁盤的 4 種類型: Images:所有鏡像占用的空間,包括拉取下來的鏡像,和本地構建的。 Con...
requests實現全自動PPT模板
http://www.1ppt.com/moban/ 可以免費的下載PPT模板,當然如果要人工一個個下,還是挺麻煩的,我們可以利用requests輕松下載 訪問這個主頁,我們可以看到下面的樣式 點每一個PPT模板的圖片,我們可以進入到詳細的信息頁面,翻到下面,我們可以看到對應的下載地址 點擊這個下載的按鈕,我們便可以下載對應的PPT壓縮包 那我們就開始做吧 首先,查看網頁的源代碼,我們可以看到每一...
猜你喜歡
Linux C系統編程-線程互斥鎖(四)
互斥鎖 互斥鎖也是屬于線程之間處理同步互斥方式,有上鎖/解鎖兩種狀態。 互斥鎖函數接口 1)初始化互斥鎖 pthread_mutex_init() man 3 pthread_mutex_init (找不到的情況下首先 sudo apt-get install glibc-doc sudo apt-get install manpages-posix-dev) 動態初始化 int pthread_...
統計學習方法 - 樸素貝葉斯
引入問題:一機器在良好狀態生產合格產品幾率是 90%,在故障狀態生產合格產品幾率是 30%,機器良好的概率是 75%。若一日第一件產品是合格品,那么此日機器良好的概率是多少。 貝葉斯模型 生成模型與判別模型 判別模型,即要判斷這個東西到底是哪一類,也就是要求y,那就用給定的x去預測。 生成模型,是要生成一個模型,那就是誰根據什么生成了模型,誰就是類別y,根據的內容就是x 以上述例子,判斷一個生產出...
styled-components —— React 中的 CSS 最佳實踐
https://zhuanlan.zhihu.com/p/29344146 Styled-components 是目前 React 樣式方案中最受關注的一種,它既具備了 css-in-js 的模塊化與參數化優點,又完全使用CSS的書寫習慣,不會引起額外的學習成本。本文是 styled-components 作者之一 Max Stoiber 所寫,首先總結了前端組件化樣式中的最佳實踐原則,然后在此基...