Spring Boot – 将 html 页面转化为 pdf 文件

Spring Boot - 将 html 页面转化为 pdf 文件

废话不多说,先看效果图。

本示例重要功能点:

  • 访问 url 直接下载 pdf 文件,前后端分离的项目可能通过这种方式下载 pdf 文件;
  • 将 html 页面(含中文、图片)转换成 pdf 文件

技术栈:

  • Flying Saucer
  • thymeleaf

1、创建 Spring Boot 项目

进入 http://start.spring.io 创建 Spring Boot 项目,Spring Boot 版本为 2.7.0,选择如下依赖:

  • Starter:spring-boot-starter-web
  • spring-boot-starter-thymeleaf
  • lombok

2、修改 pom.xml 文件,添加将 html 页面转换成 pdf 文件需要的依赖:

org.xhtmlrenderer flying-saucer-pdf 9.1.22 commons-io commons-io 2.11.0 ognl ognl 3.1.29 com.github.jtidy jtidy 1.0.2

3、创建演示数据需要的实体类 —— Student.java

import lombok.Builder;import lombok.Data;@Data@Builderpublic class Student { private Integer id; private String name; private String gender; private Integer age;}

4、创建具体的业务处理类 —— PdfService.java

import com.lowagie.text.DocumentException;import com.lowagie.text.pdf.BaseFont;import com.wangc.downloadpdf.entity.Student;import lombok.extern.slf4j.Slf4j;import org.springframework.stereotype.Service;import org.thymeleaf.TemplateEngine;import org.thymeleaf.context.Context;import org.w3c.tidy.Tidy;import org.xhtmlrenderer.pdf.ITextRenderer;import javax.annotation.Resource;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.UnsupportedEncodingException;import java.nio.charset.StandardCharsets;import java.util.List;@Slf4j@Servicepublic class PdfService { @Resource private TemplateEngine templateEngine; public ByteArrayInputStream exportPdf(String template, List students) throws Exception { Context context = new Context(); context.setVariable(“students”, students); String content = convertToXhtml(templateEngine.process(template, context)); ByteArrayInputStream byteArrayInputStream = null; try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ITextRenderer renderer = new ITextRenderer(); renderer.getFontResolver().addFont(“c:/Windows/Fonts/simsun.ttc”, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); renderer.setDocumentFromString(content); renderer.layout(); renderer.createPDF(byteArrayOutputStream, false); renderer.finishPDF(); byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); } catch (DocumentException e) { log.error(e.getMessage(), e); } return byteArrayInputStream; } private String convertToXhtml(String htmlContent) throws UnsupportedEncodingException { Tidy tidy = new Tidy(); tidy.setInputEncoding(“UTF-8”); tidy.setOutputEncoding(“UTF-8”); tidy.setXHTML(true); ByteArrayInputStream inputStream = new ByteArrayInputStream(htmlContent.getBytes(StandardCharsets.UTF_8)); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); tidy.parseDOM(inputStream, outputStream); return outputStream.toString(“UTF-8”); }}

5、创建控制器 —— PdfController.java

import com.wangc.downloadpdf.entity.Student;import com.wangc.downloadpdf.service.PdfService;import org.apache.commons.io.IOUtils;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.servlet.ModelAndView;import javax.annotation.Resource;import javax.servlet.http.HttpServletResponse;import java.io.ByteArrayInputStream;import java.util.List;import java.util.stream.Collectors;import java.util.stream.IntStream;@Controllerpublic class PdfController { @Resource private PdfService pdfService; @GetMapping(“/downloadPdf”) public void downloadPdf(HttpServletResponse response) throws Exception { List students = createTestData(); ByteArrayInputStream byteArrayInputStream = pdfService.exportPdf(“students”, students); response.setContentType(“application/octet-stream”); response.setHeader(“Content-Disposition”, “attachment; filename=receipt.pdf”); IOUtils.copy(byteArrayInputStream, response.getOutputStream()); } // 效果预览 @GetMapping(“/view”) public ModelAndView view() throws Exception { List students = createTestData(); ModelAndView mv = new ModelAndView(); mv.setViewName(“students”); mv.addObject(“students”, students); return mv; } // 测试数据 private List createTestData() { final List students = IntStream.range(1, 10) .mapToObj(v -> Student.builder() .id(v) .name(“学生” + v) .age(16) .gender(v % 2 == 0 ? “男” : “女”) .build()) .collect(Collectors.toList()); return students; }}

6、创建 html 模板 —— students.html

Students View body { /* 宋体 */ font-family:SimSun; font-size: 12px; }

Id 姓名 性别 年龄

7、启动项目

访问 http://localhost:9090/view 查看 html 页面效果。访问 http://localhost:9090/downloadPdf 下载 pdf 文件。

郑重声明:本文内容及图片均整理自互联网,不代表本站立场,版权归原作者所有,如有侵权请联系管理员(admin#wlmqw.com)删除。
用户投稿
上一篇 2022年6月16日 06:18
下一篇 2022年6月16日 06:19

相关推荐

  • 30个无加盟费的项目(茶颜悦色奶茶店加盟费多少)

    茶颜悦色又爆了,8月18日,茶颜悦色南京门店正式开业,开张不到半小时,门店就人满为患,消费者的购买热情十分高涨,而由于人流量过大造成拥堵,茶颜悦色也不得不暂停营业。 当然,这里面排…

    2022年11月27日
  • 净利润率越高越好吗(净利润率多少合适)

    一、持续增收不增利,平均净利润率首次跌入个位数 2021年,增收不增利依旧是行业主流。具体来看,大部分企业营业收入呈增长态势,E50企业平均同比增速达到17.3%,但是利润增速则明…

    2022年11月26日
  • 世界杯海外直播在哪看(中国女篮世界杯直播)

    最近一段时间最火爆的话题就是世界杯了,大家都想第一时间观看直播比赛,一些海外小伙伴在问世界杯海外直播在哪看?2022年世界杯海外直播免费观看平台有哪些?下面小编为大家带来世界杯海外…

    2022年11月25日
  • 规范透明促PPP高质量发展——16万亿元大市场迎来新规

    近日,财政部印发《关于进一步推动政府和社会资本合作(PPP)规范发展、阳光运行的通知》,从做好项目前期论证、推动项目规范运作、严防隐性债务风险、保障项目阳光运行四个方面进一步规范P…

    2022年11月25日
  • 拼多多百亿补贴预售一般多久发货(拼多多百亿补贴预售)

    拼多多里面有很多优惠活动,其中百亿补贴活动非常火爆,一些里面的东西价格比别的平台便宜,质量也有保障,还有预售的活动,那么拼多多百亿补贴预售一般多久发货?下面小编为大家带来拼多多百亿…

    2022年11月25日
  • 推荐3种白手起家的赚钱项目(白手起家赚钱项目有哪些)

    如今社会压力非常的大,家有老少要养活,这些都加速了穷人想要创业的欲望,但是创业路总是那么的艰难,资金就是创业的重头戏,所以选择一个低成本又赚钱的项目是大多数人最期望的了,那么有哪些…

    2022年11月25日
  • 百度关键词快速排名的4大原理解析(百度怎么刷关键词)

    近期百度公告惊雷算法2.0,升级之快还是第一次吧,看来百度对于刷点击行为是零容忍了。之前尹华峰SEO技术博客介绍过一篇如何使用刷点击工具,其实市面上有很多这类SEO快速排名的软件,…

    2022年11月25日
  • 科比19岁女儿遭自称与她生“科比式孩子”男子跟踪骚扰

    极目新闻记者王亮亮黄佳琪 据福克斯新闻网报道,当地时间11月21日,已故篮球巨星科比·布莱恩特的长女娜塔莉亚·布莱恩特21日向法院提交临时限制令,声称这位32岁的前科从十几岁起就骚…

    2022年11月24日
  • 《金铲铲之战》s8赛季羁绊有哪些 s8赛季羁绊大全

    《金铲铲之战》最近也快更新s8赛季了,增加了许多好玩有趣的新羁绊以及一些以前版本的羁绊也回归了,那么新增加的羁绊都有些什么呢?下面让我们一起来看看吧! 《金铲铲之战》s8赛季羁绊大…

    2022年11月24日
  • Steam秋季特卖开启 为Steam大奖提名游戏

    Steam秋季特卖开启 为Steam大奖提名游戏 Steam秋季特卖活动现已正式开启,时间从11月23日持续到11月30日(北京时间),新老游戏均有不错的折扣,感兴趣的玩家可以前往…

    2022年11月24日

联系我们

联系邮箱:admin#wlmqw.com
工作时间:周一至周五,10:30-18:30,节假日休息