maven配置## 标题

  <!--         https://mvnrepository.com/artifact/com.itextpdf/itextpdf --><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.13</version></dependency><!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian --><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency><dependency><groupId>org.xhtmlrenderer</groupId><artifactId>flying-saucer-pdf</artifactId><version>9.1.12</version></dependency>

pdf工具类## 标题

package cn.prop.fm.pdf;import com.itextpdf.text.pdf.BaseFont;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.util.List;
import java.util.Map;/*** 功能:pdf处理工具类** @author qust* @version 1.0 2018/2/23 17:21*/
public class PdfUtils {private PdfUtils() {}private static final Logger LOGGER = LoggerFactory.getLogger(PdfUtils.class);/*** 按模板和参数生成html字符串,再转换为flying-saucer识别的Document** @param templateName freemarker模板名称* @param variables    freemarker模板参数* @return Document*/private static Document generateDoc(FreeMarkerConfigurer configurer, String templateName, Map<String, Object> variables) {Template tp;try {tp = configurer.getConfiguration().getTemplate(templateName);} catch (IOException e) {LOGGER.error(e.getMessage(), e);return null;}StringWriter stringWriter = new StringWriter();try (BufferedWriter writer = new BufferedWriter(stringWriter)) {try {tp.process(variables, writer);writer.flush();} catch (TemplateException e) {LOGGER.error("模板不存在或者路径错误", e);} catch (IOException e) {LOGGER.error("IO异常", e);}DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();return builder.parse(new ByteArrayInputStream(stringWriter.toString().getBytes()));} catch (Exception e) {LOGGER.error(e.getMessage(), e);return null;}}/*** 核心: 根据freemarker模板生成pdf文档** @param configurer   freemarker配置* @param templateName freemarker模板名称* @param out          输出流* @param listVars     freemarker模板参数* @throws Exception 模板无法找到、模板语法错误、IO异常*/private static void generateAll(FreeMarkerConfigurer configurer, String templateName, OutputStream out, List<Map<String, Object>> listVars) throws Exception {if (CollectionUtils.isEmpty(listVars)) {LOGGER.warn("警告:freemarker模板参数为空!");return;}ITextRenderer renderer = new ITextRenderer();Document doc = generateDoc(configurer, templateName, listVars.get(0));renderer.setDocument(doc, null);//设置字符集(宋体),此处必须与模板中的<bodystyle="font-family: SimSun">一致,区分大小写,不能写成汉字"宋体"//设置字符集(宋体),此处必须与模板中的<bodystyle="font-family: SimSun">一致,区分大小写,不能写成汉字"宋体"ITextFontResolver fontResolver = renderer.getFontResolver();fontResolver.addFont("simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//展现和输出pdfrenderer.layout();renderer.createPDF(out, false);//根据参数集个数循环调用模板,追加到同一个pdf文档中//(注意:此处从1开始,因为第0是创建pdf,从1往后则向pdf中追加内容)for (int i = 1; i < listVars.size(); i++) {Document docAppend = generateDoc(configurer, templateName, listVars.get(i));renderer.setDocument(docAppend, null);renderer.layout();renderer.writeNextDocument(); //写下一个pdf页面}renderer.finishPDF(); //完成pdf写入}/*** pdf下载** @param configurer   freemarker配置* @param templateName freemarker模板名称(带后缀.ftl)* @param listVars     模板参数集* @param response     HttpServletResponse* @param fileName     下载文件名称(带文件扩展名后缀)*/public static void download(FreeMarkerConfigurer configurer, String templateName, List<Map<String, Object>> listVars, HttpServletResponse response, String fileName) {// 设置编码、文件ContentType类型、文件头、下载文件名response.setCharacterEncoding("utf-8");response.setContentType("application/force-download");try {response.setHeader("Content-Disposition", "attachment;fileName=" +new String(fileName.getBytes("gb2312"), "ISO8859-1"));} catch (UnsupportedEncodingException e) {LOGGER.error(e.getMessage(), e);}try (ServletOutputStream out = response.getOutputStream()) {generateAll(configurer, templateName, out, listVars);} catch (Exception e) {LOGGER.error(e.getMessage(), e);}}/*** pdf预览** @param configurer   freemarker配置* @param templateName freemarker模板名称(带后缀.ftl)* @param listVars     模板参数集* @param response     HttpServletResponse*/public static void preview(FreeMarkerConfigurer configurer, String templateName, List<Map<String, Object>> listVars, HttpServletResponse response) {try (ServletOutputStream out = response.getOutputStream()) {generateAll(configurer, templateName, out, listVars);out.flush();} catch (Exception e) {LOGGER.error(e.getMessage(), e);}}
}

controller层## 标题

package cn.prop.fm.pdf;import cn.prop.fm.vo.MerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;/*** 功能:pdf预览、下载**/
@Controller
@RequestMapping(value = "/pdf")
public class PdfController {@Autowiredprivate FreeMarkerConfigurer configurer;/*** pdf预览** @param request  HttpServletRequest* @param response HttpServletResponse*/@RequestMapping(value = "/preview", method = RequestMethod.GET)public void preview(HttpServletRequest request, HttpServletResponse response) {// 构造freemarker模板引擎参数,listVars.size()个数对应pdf页数List<Map<String, Object>> listVars = new ArrayList<>();List<MerVO> a = new LinkedList<>();MerVO s = new MerVO();s.setMerId("1");s.setMerName("1wewe");MerVO b = new MerVO();b.setMerId("1");b.setMerName("1wewe");a.add(s);a.add(b);Map<String, Object> variables = new HashMap<>();variables.put("title", "测试预览ASGX!");variables.put("list", a);listVars.add(variables);PdfUtils.preview(configurer, "pdfPage.ftl", listVars, response);}/*** pdf下载** @param request  HttpServletRequest* @param response HttpServletResponse*/@RequestMapping(value = "/download", method = RequestMethod.GET)public void download(HttpServletRequest request, HttpServletResponse response) {List<Map<String, Object>> listVars = new ArrayList<>();Map<String, Object> variables = new HashMap<>();variables.put("title", "测试下载ASGX!");listVars.add(variables);PdfUtils.download(configurer, "pdfPage.ftl", listVars, response, "测试中文.pdf");}
}

ftl模板## 标题

提示:样式需要更加实际情况调整,与html的页面布局有差异

<!DOCTYPE html>
<html>
<head lang="en"><title>Spring Boot Demo - PDF</title><style>margin:0,0;body{ text-align:center}#divcss{margin:0 auto;width:100%;height:50%;}table {border-collapse: collapse;text-align:center;}table, td, th {border: 1px solid black;}</style>
</head>
<bodystyle="font-family: 'SimSun'">
<div id="divcss"><divstyle="text-align:center"><h2>物业名</h2><h3>202006账单结算通知单</h3></div><divstyle=""><divstyle="width:50%;height: 100%;float:left;"><span>楼号/房号:1栋-2楼-201</span><br></br><span>租户名:孙悟空</span></div><divstyle="height: 100%;float:right"><p>账单周期:2020-06-01至2020-06-261</p></div></div><divstyle="clear: both"><table border="1"style="width: 100%"><tr><th>抄表费用</th><th>表计表号</th><th>上期读数</th><th>本期读数</th><th>总用电量</th><th>费用金额</th></tr><tr><td>电费</td><td>000000001221</td><td>2020-03-31</td><td>2020-03-31</td><td>50.84</td><td>50.84</td></tr><tr><td colspan="6">其它费用项</td></tr><tr><td colspan="6">测试固定收费:¥100  </td></tr></table></div><divstyle="border-bottom: 1px solid;border-left: 1px solid;border-right: 1px solid;height: 140px;text-align: center;margin-top: -18px;"><h3>此处为支付方式区域</h3><spanstyle="
position: relative;
top: 30px;">温馨提示:请贵公司及时缴清费用,以免逾期后自动断电影响正常用电,入有疑问,请致电服务热线。</span></div><div><spanstyle="margin-right: 8%;">制表人:车小明是的</span><span >   打印日期:2020-08-23 09:23</span></div>
</div>
</body>
</html>

springboot pdf浏览与下载相关推荐

  1. PDF文档在线浏览防下载加密方案

    PDF文档在线浏览防下载加密方案 (在线浏览防下载,文件不落地.禁止打印.禁止另存.禁止文字复制.动态添加防截图水印) 本方案针对PDF文档在线浏览的版权保护. 其突出特点表现在: 在线浏览防下载,文 ...

  2. pdf 无须浏览直接下载

    最近页面有下载pdf需求,之前a标签有自带的图片下载,但是pdf浏览器默认会自动浏览打开,介绍一下此方法浏览器无须打开其他页面进行下载文件 浏览器 pdf 无须浏览直接下载 支持多种文件下载 down ...

  3. springBoot+layui 压缩包 直接下载--或--直接压缩并下载方法

    springBoot+layui 压缩包 直接下载–或--直接压缩并下载方法 前端代码 layer.confirm('您确定要下载 ' + data.fileZipName + ' 吗?', {ico ...

  4. JAVA根据word模板生成合同,并能实现网页在线浏览/打印/下载

    最近, 项目有这样一个需求:       根据我选择的模板(docx文件),和我表单填的数据,生成相应的合同文件(docx),该合同要能网页在线浏览/打印/下载在合同中还要放置签字图片和身份证图片 我 ...

  5. springBoot下的ftp下载

    springBoot下的ftp下载 springboot-Environment ftp登录.退出 打包下载 本实例将创建一个ftp打包文件的工具类 Environment类获取配置信息 spring ...

  6. springboot pdf模板打印

    springboot pdf模板打印 1.下载Adobe Acrobat DC工具来制作pdf的模板 打开一个pdf 2.制作pdf模板 把自动生成的文本框删除 然后 拖入文本框并自定义键 导入mav ...

  7. pdf阅读器下载官方下载

    pdf格式不能编辑怎么办?pdf格式不能修改怎么办?这些问题都会影响到大家的工作效率.其实大家都很清楚pdf格式的优点就是在于浏览与阅读,并不适用于编辑与修改.那么今天小编就来与大家分享一个不仅可以阅 ...

  8. JavaScript前端:与PDF.js结合,实现网页PDF内容批量下载

    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 JavaScript前端:与PDF.js结合,实现网页PDF内容批量下载 前言 一.PDF.js是什么? 二.PDF.js单个PDF文 ...

  9. python下载教程pdf-Python教程PDF合集下载

    Python教程PDF合集下载,大量Python学习资料大合辑,目录如下: BanditAlgorithms.pdf FlaskWeb开发基于Python.pdf fluentpython.pdf P ...

最新文章

  1. 设计模式在我工作中的巧妙实践
  2. 重磅|我国科学家成功研制全球神经元规模最大的类脑计算机
  3. Jfinal 2.1版本,JFinalConfig里自动配置路由的代码实现,直接晒代码
  4. python c++操作raw文件
  5. 网站特效-------旋转的图片
  6. 【opencv系列02】OpenCV4.X图像读取与显示
  7. 10.8 ss:查看网络状态
  8. python字符串处理函数汇总_Python内置的字符串处理函数详细整理(覆盖日常所用)...
  9. Web开发之三:前后端开发任务量分析与比较
  10. 从俄罗斯方块到星际2,全都用得上:DeepMind无监督分割大法,为游戏而生
  11. MIUI 12稳定版系统中的开发者选项限制解除
  12. java 视频分辨率_javaCV开发详解之15:视频帧像素格式转换
  13. git 将暂存区文件提交_git文件状态,暂存与提交
  14. photo2cartoon环境搭建-真人头像卡通画-写实
  15. 抽象基类与接口,共性与个性的选择
  16. Linux OS7 常用
  17. Jekyll+GitHub搭建个人博客
  18. 【Leetcode】644. Maximum Average Subarray II
  19. 如何让一个内向的人锻炼与人交流能力?
  20. html中的开启礼盒的代码,CSS3 蛋糕+生日礼盒打开动效

热门文章

  1. 管理故事:授人以鱼,不如授人以渔
  2. PolyPhen:分析人类非同义突变对蛋白质的影响
  3. HGVS基因突变命名规则
  4. Aseprite完全指南(动画精灵编辑器和像素艺术工具)
  5. 雅克比迭代法的例子matlab,MATLAB样例之雅克比迭代法
  6. 百度地图、高德地图、谷歌地图离线瓦片下载研究(一)
  7. 软件测试方法汇总,软件测试方法和技术总结.ppt
  8. 拍领导牵手的摄影师立功还是担责?
  9. 准度(准确度)和精度(精密度)
  10. 基于 Vue2 实现元素拖拽的全局指令,快速赋予任意元素可拖拽能力