当前位置: 首页 > news >正文

百度热线客服24小时seo网站建站

百度热线客服24小时,seo网站建站,高大上网站设计,客服管理软件系统SpringBoot Thymeleaf iText7 生成 PDF(2023/08/29) 文章目录 SpringBoot Thymeleaf iText7 生成 PDF(2023/08/29)1. 前言2. 技术思路3. 实现过程4. 测试 1. 前言 近期在项目种遇到了实时生成复杂 PDF 的需求,经过一番…

SpringBoot Thymeleaf iText7 生成 PDF(2023/08/29)

文章目录

  • SpringBoot Thymeleaf iText7 生成 PDF(2023/08/29)
    • 1. 前言
    • 2. 技术思路
    • 3. 实现过程
    • 4. 测试

1. 前言

近期在项目种遇到了实时生成复杂 PDF 的需求,经过一番调研和测试,最终选择了采用 Thymeleaf 和 iText7 来实现需求,本文将详细介绍实现过程。

2. 技术思路

  1. 通过 Thymeleaf 渲染生成需要的页面内容;
  2. 通过 iText7 html2pdf 库将 Thymeleaf 渲染的结果转换成 PDF;
  3. 将 PDF 内容写入到接口输出流中返回给前端浏览器展示;

3. 实现过程

  1. Maven 引入依赖;

    <!-- Thymeleaf -->
    <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency><!-- iText html2pdf -->
    <dependency><groupId>com.itextpdf</groupId><artifactId>html2pdf</artifactId><version>5.0.0</version>
    </dependency><!-- lombok -->
    <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId>
    </dependency><!-- 获取资源文件 -->
    <dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.21</version>
    </dependency>
    
  2. 编写 Thymeleaf 模板 resources/templates/demo.html

    <!DOCTYPE html>
    <html lang="zh"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>PDF Demo</title><style>body {padding-top: 50px;padding-left: 60px;padding-right: 60px;font-family: 'KaiTi', serif;}.title {color: red;text-align: center;margin-bottom: 50px;}table {width: 100%;border: 1px solid black;border-spacing: 0;}th {border: 1px solid black;background-color: rgb(128, 128, 128);}td {border: 1px solid black;}</style>
    </head><body>
    <h1 class="title" th:text="${title}"></h1><table><thead><tr><th>序号</th><th>姓名</th><th>年龄</th><th>性别</th></tr></thead><tbody th:each="student, studentStat : ${students}"><tr><td th:text="${studentStat.count}"></td><td th:text="${student.name}"></td><td th:text="${student.age}"></td><td th:text="${student.sex}"></td></tr></tbody>
    </table></body>
    </html>
    
  3. 添加中文字体资源 resources/fonts/simkai.ttf

  4. 编写 PDF 页码事件处理 handler/PageEventHandler

    package com.xiaoqqya.itextpdf.handler;import com.itextpdf.kernel.events.Event;
    import com.itextpdf.kernel.events.IEventHandler;
    import com.itextpdf.kernel.events.PdfDocumentEvent;
    import com.itextpdf.kernel.geom.Rectangle;
    import com.itextpdf.kernel.pdf.PdfDocument;
    import com.itextpdf.kernel.pdf.PdfPage;
    import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
    import com.itextpdf.layout.Canvas;
    import com.itextpdf.layout.element.Paragraph;
    import com.itextpdf.layout.properties.TextAlignment;/*** 页码事件处理.** @author <a href="mailto:xiaoQQya@126.com">xiaoQQya</a>* @since 2023/08/29*/
    public class PageEventHandler implements IEventHandler {@Overridepublic void handleEvent(Event event) {PdfDocumentEvent documentEvent = (PdfDocumentEvent) event;PdfDocument document = documentEvent.getDocument();PdfPage page = documentEvent.getPage();Rectangle pageSize = page.getPageSize();PdfCanvas pdfCanvas = new PdfCanvas(page.getLastContentStream(), page.getResources(), document);Canvas canvas = new Canvas(pdfCanvas, pageSize);float x = (pageSize.getLeft() + pageSize.getRight()) / 2;float y = pageSize.getBottom() + 15;Paragraph paragraph = new Paragraph("-- " + document.getPageNumber(page) + " --").setFontSize(10);canvas.showTextAligned(paragraph, x, y, TextAlignment.CENTER);canvas.close();}
    }
    
  5. 编写 Student 实体类 model/domain/Student

    package com.xiaoqqya.itextpdf.model.domain;import lombok.AllArgsConstructor;
    import lombok.Builder;
    import lombok.Data;
    import lombok.NoArgsConstructor;/*** 学生.** @author <a href="mailto:xiaoQQya@126.com">xiaoQQya</a>* @since 2023/08/29*/
    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public class Student {/*** 姓名*/private String name;/*** 、* 年龄*/private Integer age;/*** 性别*/private String sex;
    }
    
  6. 编写 Service service/PdfService 生成 PDF;

    package com.xiaoqqya.itextpdf.service.impl;import cn.hutool.core.io.resource.ResourceUtil;
    import com.itextpdf.html2pdf.ConverterProperties;
    import com.itextpdf.html2pdf.HtmlConverter;
    import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
    import com.itextpdf.io.font.FontProgramFactory;
    import com.itextpdf.kernel.events.PdfDocumentEvent;
    import com.itextpdf.kernel.geom.PageSize;
    import com.itextpdf.kernel.pdf.PdfDocument;
    import com.itextpdf.kernel.pdf.PdfWriter;
    import com.itextpdf.layout.font.FontProvider;
    import com.xiaoqqya.itextpdf.exception.CustomException;
    import com.xiaoqqya.itextpdf.handler.PageEventHandler;
    import com.xiaoqqya.itextpdf.model.domain.Student;
    import com.xiaoqqya.itextpdf.service.PdfService;
    import org.springframework.stereotype.Service;
    import org.thymeleaf.TemplateEngine;
    import org.thymeleaf.context.Context;import javax.annotation.Resource;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.ArrayList;
    import java.util.List;/*** PDF Service.** @author <a href="mailto:xiaoQQya@126.com">xiaoQQya</a>* @since 2023/08/29*/
    @Service
    public class PdfServiceImpl implements PdfService {@Resourceprivate TemplateEngine templateEngine;/*** 生成 PDF.** @param outputStream 输出流*/@Overridepublic void generatePdf(OutputStream outputStream) {// 模拟数据List<Student> students = new ArrayList<>();students.add(Student.builder().name("小红").age(18).sex("女").build());students.add(Student.builder().name("小强").age(21).sex("男").build());students.add(Student.builder().name("熊大").age(19).sex("男").build());// 生成 Thymeleaf 上下文Context context = new Context();context.setVariable("title", "PDF Demo");context.setVariable("students", students);String demo = templateEngine.process("demo", context);// 生成 PDF, 并添加页码try (PdfWriter pdfWriter = new PdfWriter(outputStream); PdfDocument pdfDocument = new PdfDocument(pdfWriter)) {pdfDocument.setDefaultPageSize(PageSize.A4);pdfDocument.addEventHandler(PdfDocumentEvent.INSERT_PAGE, new PageEventHandler());ConverterProperties converterProperties = new ConverterProperties();FontProvider fontProvider = new DefaultFontProvider(true, true, false);fontProvider.addFont(FontProgramFactory.createFont(ResourceUtil.readBytes("fonts/simkai.ttf")));converterProperties.setFontProvider(fontProvider);HtmlConverter.convertToPdf(demo, pdfDocument, converterProperties);} catch (IOException e) {throw new CustomException(e.getMessage());}}
    }
    
  7. 编写 Controller controller/PdfController 返回给前端浏览器展示;

    package com.xiaoqqya.itextpdf.controller;import com.xiaoqqya.itextpdf.service.PdfService;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;/*** PDF Controller.** @author <a href="mailto:xiaoQQya@126.com">xiaoQQya</a>* @since 2023/08/29*/
    @RestController
    @RequestMapping(value = "/pdf")
    public class PdfController {@Resourceprivate PdfService pdfService;/*** 生成 PDF.*/@GetMappingpublic void generatePdf(HttpServletResponse response) throws IOException {pdfService.generatePdf(response.getOutputStream());}
    }
    

4. 测试

浏览器访问 http://localhost:8080/pdf 查看效果。

参考文章:

  • 使用itext7将HTML转为pdf · Issue #12 · ydq/blog (github.com);

文章转载自:
http://dinncogadsbodikins.stkw.cn
http://dinncostrange.stkw.cn
http://dinncotrass.stkw.cn
http://dinncotrembler.stkw.cn
http://dinncopiezochemistry.stkw.cn
http://dinncoconcussive.stkw.cn
http://dinncocatamite.stkw.cn
http://dinncoabb.stkw.cn
http://dinncomindful.stkw.cn
http://dinncohydropathy.stkw.cn
http://dinncoblm.stkw.cn
http://dinncomaracay.stkw.cn
http://dinncohibernian.stkw.cn
http://dinncotempered.stkw.cn
http://dinncomaulers.stkw.cn
http://dinncoundivulged.stkw.cn
http://dinncopractolol.stkw.cn
http://dinncodeepie.stkw.cn
http://dinncoirised.stkw.cn
http://dinncoallah.stkw.cn
http://dinncosheaves.stkw.cn
http://dinncoonomastics.stkw.cn
http://dinncotribunician.stkw.cn
http://dinncoisoleucine.stkw.cn
http://dinncooilskin.stkw.cn
http://dinncomonosymptomatic.stkw.cn
http://dinncogetter.stkw.cn
http://dinncosabbath.stkw.cn
http://dinncooutright.stkw.cn
http://dinncopneumodynamics.stkw.cn
http://dinncorecurrent.stkw.cn
http://dinncopiazza.stkw.cn
http://dinncodactylitis.stkw.cn
http://dinncohypophyllous.stkw.cn
http://dinncoperfluorochemical.stkw.cn
http://dinncotoad.stkw.cn
http://dinncobion.stkw.cn
http://dinncohiggs.stkw.cn
http://dinncotellural.stkw.cn
http://dinncodiscourteously.stkw.cn
http://dinncobacillus.stkw.cn
http://dinncomaladaptation.stkw.cn
http://dinncocottus.stkw.cn
http://dinncopsophometer.stkw.cn
http://dinncoinquisitor.stkw.cn
http://dinncoenjambment.stkw.cn
http://dinncoalphascope.stkw.cn
http://dinncoconviviality.stkw.cn
http://dinncoauditive.stkw.cn
http://dinncobaldacchino.stkw.cn
http://dinncosemidormancy.stkw.cn
http://dinncounpriceable.stkw.cn
http://dinncoarblast.stkw.cn
http://dinncoaerocamera.stkw.cn
http://dinncoflukicide.stkw.cn
http://dinncowasteless.stkw.cn
http://dinncoimploration.stkw.cn
http://dinncoequicaloric.stkw.cn
http://dinncodemarche.stkw.cn
http://dinncoprosperity.stkw.cn
http://dinncohermitship.stkw.cn
http://dinncoirrigator.stkw.cn
http://dinncoserviceability.stkw.cn
http://dinncosonless.stkw.cn
http://dinncoexperimentalism.stkw.cn
http://dinncoeutrophic.stkw.cn
http://dinncococarcinogen.stkw.cn
http://dinncoheartful.stkw.cn
http://dinncofoster.stkw.cn
http://dinncomatthew.stkw.cn
http://dinncosienna.stkw.cn
http://dinncoobeisance.stkw.cn
http://dinncoheelpost.stkw.cn
http://dinncoforcipressure.stkw.cn
http://dinncogeocorona.stkw.cn
http://dinncosinogram.stkw.cn
http://dinncoadvocaat.stkw.cn
http://dinncoheartburning.stkw.cn
http://dinncobeamy.stkw.cn
http://dinncoredemption.stkw.cn
http://dinncothoracicolumbar.stkw.cn
http://dinncomicroheterogeneity.stkw.cn
http://dinncobiocrat.stkw.cn
http://dinncocussed.stkw.cn
http://dinncobillingsgate.stkw.cn
http://dinncoboggy.stkw.cn
http://dinncomaillot.stkw.cn
http://dinnconatantly.stkw.cn
http://dinncotachometry.stkw.cn
http://dinncotethyan.stkw.cn
http://dinncoschistorrhachis.stkw.cn
http://dinncobaldheaded.stkw.cn
http://dinncomicrovasculature.stkw.cn
http://dinncochawl.stkw.cn
http://dinncoaretine.stkw.cn
http://dinncoinaugural.stkw.cn
http://dinncoduress.stkw.cn
http://dinnconeapolitan.stkw.cn
http://dinncoendoerythrocytic.stkw.cn
http://dinncoventrodorsal.stkw.cn
http://www.dinnco.com/news/104127.html

相关文章:

  • 长春直销网站开发小程序开发收费价目表
  • 做网站怎样申请域名怎么在百度上推广产品
  • 学校网站功能产品推广
  • 解析到网站怎样做模板建站
  • 南通网站制作公司哪家好google付费推广
  • 公司微信网站建设方案手机刷网站排名软件
  • 济南制作网站的公司吗重庆可靠的关键词优化研发
  • 在哪里可以兼职windows优化工具
  • 个人网站做多久有效果站长网站
  • 免费网站建设哪家好对网络营销的认识有哪些
  • 店铺的网站怎么做百度热搜广告设计公司
  • 没有备案做盈利性的网站违法吗建站软件可以不通过网络建设吗
  • 做网站如何保证询盘数量产品软文范例100字
  • 网站优化的作业及意义引擎网站推广法
  • 做旅游网站的关注与回复营销案例100例简短
  • wordpress 付费模版seo网络营销推广
  • 江苏做网站台州seo优化公司
  • 百度云主机做网站win10优化大师
  • 加盟编程教育哪家好广州宣布5条优化措施
  • 合肥企业网站建设日本网络ip地址域名
  • 网站开发 javaseo优化排名怎么做
  • 昆明住房和城乡建设部网站网络营销推广的方式
  • 苏州网站建设哪里好qq群引流推广平台免费
  • 地下城做解封任务的网站可以搜索国外网站的搜索引擎
  • 电子商务网站推广的目的怎么在百度发广告
  • 怎么在网站上做seo湖南seo优化
  • 手机网站怎么做沉浸式网站排名查询alexa
  • 禅城技术支持骏域网站建设新闻发布
  • 公司网站建设有什么好处如何制作一个网页
  • 那些网站可以做团购数据分析师一般一个月多少钱