最近项目中要把相关数据导出为PDF文件,总结下自己写这个功能遇到的种种问题
先给出个大概的框架
package com.xsm;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import com.sectechio.fintechmon.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;
}
}
更多推荐
HTML 模板+freemarker渲染 生成PDF(一)
发布评论