一、 制作模板
请参考上一篇博客
二、 代码实现读取数据库数据 ,并输出到PDF上
- 读取数据库,获取数据。代码如下:
<!--Maven-->
<!--生成PDF的类库-->
<dependency>
<groupId>com.aspose.words</groupId>
<artifactId>aspose-words</artifactId>
<version>15.8.0</version>
</dependency>
<!--spring-web 版本 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
import com.aspose.words.Document;
import com.hhwy.wdst.common.util.FreemarkerUtil;
import org.apache.commons.codec.binary.Base64;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class test {
/**
* @return ResponseEntity<InputStreamResource>
* @throws Exception
* @author dzk
* @tittle download
* @description 下载PDF 数据回显
* @date 2020年11月24日 15:56:20
*/
public ResponseEntity<InputStreamResource> download(String id, HttpServletResponse response, HttpServletRequest request) throws Exception {
//桌面
String filePath = "C:/Users/lenovo/Desktop/";
//ftl 文件名称
String ftlName = "test_ft.ftl";
// ftl中需要遍历的数据
Map dataList = new HashMap();
//此处为从数据库读取数据
List<Map> list = dao.get("test.sql.getData", id);
dataList.put("dataList", list);
// doc路径 工具类读取文件
String excelFile = FreemarkerUtil.renderFile(dataList, filePath, list.get(0).get("id") + ".doc", filePath, ftlName);
//生成PDF 的类库
Document document = new Document(excelFile);
//pdf命名
//走浏览器编译 名称进行转码
String pdfFileName = list.get(0).get("name") + "-" + list.get(0).get("evaluate_time") + ".pdf";
//未走浏览器编译 原样输出
String pdfFileName1 = list.get(0).get("name") + "-" + list.get(0).get("evaluate_time") + ".pdf";
document.save(filePath + pdfFileName,
com.aspose.words.SaveFormat.PDF);
// 浏览器编译 浏览器下载
String agent = (String) request.getHeader("USER-AGENT");
if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
pdfFileName = "=?UTF-8?B?"
+ (new String(Base64.encodeBase64(pdfFileName
.getBytes("UTF-8")))) + "?=";
} else if (agent != null && agent.toLowerCase().indexOf("edge") > 0) {
pdfFileName = java.net.URLEncoder.encode(pdfFileName,
"UTF-8");
} else if (agent != null
&& agent.toLowerCase().indexOf("chrome") > 0) {
pdfFileName = new String(pdfFileName.getBytes(),
"ISO-8859-1");
} else {
pdfFileName = java.net.URLEncoder.encode(pdfFileName,
"UTF-8");
}
//PDF 路径 输出的PDF名称
File pdf = new File(filePath + "/" + pdfFileName1);
FileSystemResource fileResource = new FileSystemResource(pdf);
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", String.format(
"attachment; filename=\"%s\"", pdfFileName));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
ResponseEntity<InputStreamResource> result = ResponseEntity
.ok()
.headers(headers)
.contentLength(fileResource.contentLength())
.contentType(
MediaType.parseMediaType("application/pdf"))
.body(new InputStreamResource(fileResource.getInputStream()));
//删除临时文件
if (pdf.exists()) {
pdf.delete();
}
//删除临时文件
File word = new File(excelFile);
if (word.exists()) {
word.delete();
}
return result;
}
}
- 工具类代码
import cn.hutool.core.util.ObjectUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import java.io.*;
import java.util.Locale;
/**
* Created by dzk.
*/
public class FreemarkerUtil {
private static final Logger logger = LoggerFactory.getLogger(FreemarkerUtil.class);
private static Configuration configuration = null;
static{
if(ObjectUtil.isNull(configuration))
configuration = new Configuration();
}
/**
* 渲染 ftl文件 生成缓存文件,返回渲染成功之后缓存文件的路径, 注意使用之后记得删除缓存文件
* @param model 模板中需要的模型数据
* @param ftlPath 模板路径,约定模板存放路径 resources/templates/ 可自行依据业务创建子文件目录
* @param ftlName 模板名称
* @return 渲染成功之后缓存文件的路径, 注意使用之后记得删除缓存文件
*/
public static String renderFile(Object model, String ftlPath, String ftlName) throws IOException, TemplateException {
return renderFile(model, "",System.currentTimeMillis()+".temp", ftlPath, ftlName);
}
/**
* 渲染 ftl文件到指定目录文件 ,返回渲染成功之后的文件路径
* @param model 模板中需要的模型数据
* @param outFilePath 要输出的文件位置
* @param outFileName 要输出的文件名称
* @param ftlPath 模板路径,约定模板存放路径 resources/templates/ 可自行依据业务创建子文件目录
* @param ftlName 模板名称
* @return 渲染成功之后文件的路径
*/
public static String renderFile(Object model, String outFilePath, String outFileName, String ftlPath, String ftlName) throws IOException, TemplateException {
//设置模板路径
configuration.setDirectoryForTemplateLoading(ResourceUtils.getFile(ftlPath));
configuration.setEncoding(Locale.getDefault(), "utf-8");
//加载模板文件
Template template = configuration.getTemplate(ftlName);
template.setEncoding("utf-8");
template.setOutputEncoding("utf-8");
//渲染到指定路径文件
File outFile = new File(outFilePath);
if(!outFile.exists() || outFile.isDirectory()){
outFile.mkdirs();
}
// FileWriter fileWriter = new FileWriter(new File(outFilePath + outFileName));
OutputStreamWriter fileWriter = new OutputStreamWriter(new FileOutputStream(new File(outFilePath + outFileName)),"utf-8");
template.process(model, fileWriter);
fileWriter.flush();
fileWriter.close();
logger.info(outFileName + " Generation Successful ");
// toUTF8NoBOM(outFilePath + outFileName);
return outFilePath + outFileName;
}
/**
* 渲染 ftl文件 ,返回渲染成功之后的文件内容
* @param model 模板中需要的模型数据
* @param ftlPath 模板路径,约定模板存放路径 resources/templates/ 可自行依据业务创建子文件目录
* @param ftlName 模板名称
* @return 渲染成功之后的文件内容
*/
public static String renderString(Object model, String ftlPath, String ftlName) throws IOException, TemplateException {
//获取渲染好的缓存文件
String filePath = renderFile(model, ftlPath, ftlName);
File file = new File(filePath);
//读取文件内容
BufferedReader bufferReader = new BufferedReader(new FileReader(file));
String tempString,fileContent = "";
while((tempString = bufferReader.readLine()) != null){
fileContent += tempString + "\n";
}
//关闭流并删除缓存文件
bufferReader.close(); if (file.exists()){ file.delete(); }
return fileContent;
}
}
综上,就可以根据模板生成我们想要的PDF文件啦。