IT袋

当前位置:主页 > 经验教程 > 办公教程 >

SpringBoot使用Thymeleaf生成PDF

SpringBoot使用Thymeleaf生成PDF(2)

时间:2024-01-23 15:00:16 来源:IT袋 作者:马勇
导读:SpringBoot使用Thymeleaf生成PDF,server: port: 8899spring: thymeleaf: prefix: classpath:/templates/ suffix: .html mode: HTML encoding: UTF-8 servlet: content-type: text/html cache: false 【步骤三】:创建Thymeleaf模板文件 创建

SpringBoot使用Thymeleaf生成PDF

server:
  port: 8899
spring:
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    mode: HTML
    encoding: UTF-8
    servlet:
      content-type: text/html
    cache: false

【步骤三】:创建Thymeleaf模板文件

创建Thymeleaf模板文件(例如):路径如下src/main/resources/templates/mytemplate.html

<!-- src/main/resources/templates/mytemplate.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>PDF Document</title>
</head>
<!--这样配置不中文不会显示-->
<!--<body>-->
<body>
<h1 th:text="${title}">Default Title</h1>
<p th:text="${content}">Default Content</p></body>
</html>

【步骤四】:创建PDF生成服务

创建PdfGenerationService类,该类负责将Thymeleaf模板渲染成HTML,并使用Flying Saucer将HTML转换为PDF:

@Service
public class PdfGenerationService {
    @Autowired
    private  TemplateEngine templateEngine;
    public byte[] generatePdf(Map<String, Object> data) {
        String htmlContent = templateEngine.process("mytemplate", new Context(Locale.getDefault(), data));
        return convertHtmlToPdf(htmlContent);
    }
    private byte[] convertHtmlToPdf(String htmlContent) {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            ITextRenderer renderer = new ITextRenderer();
            // 设置中文字体
            renderer.getFontResolver().addFont("templates/SimSun.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            renderer.setDocumentFromString(htmlContent);
            renderer.layout();
            renderer.createPDF(outputStream);
            return outputStream.toByteArray();
        } catch (Exception e) {
            // 处理异常
            return new byte[0];
        }
    }
}

注意:我们要设置字体,不然不支持中文

【步骤五】:创建Controller

创建一个简单的Controller,用于接收请求并调用PdfGenerationService生成PDF:

package com.zbbmeta.controller;
import com.zbbmeta.service.PdfGenerationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
 * @Author: springboot葵花宝典
 * @Github: https://github.com/bangbangzhou
 * @description: TODO
 */
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("/pdf")
public class PdfController {
    private final PdfGenerationService pdfGenerationService;
    @Autowired
    public PdfController(PdfGenerationService pdfGenerationService) {
        this.pdfGenerationService = pdfGenerationService;
    }
    @GetMapping("/generate")
    public void generatePdf(@RequestParam(defaultValue = "Custom Title") String title,
                            @RequestParam(defaultValue = "Custom Content") String content,
                            HttpServletResponse response) throws IOException {
        Map<String, Object> data = new HashMap<>();
        data.put("title", title);
        data.put("content", content);
        byte[] pdfBytes = pdfGenerationService.generatePdf(data);
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "inline; filename=generated.pdf");
        response.getOutputStream().write(pdfBytes);
        response.flushBuffer();
    }
}

相关阅读

  • excel怎么添加行列 excel表格添加行列

    excel怎么添加行列 excel表格添加行列

    文章摘要:excel怎么添加行列的生活小经验,关于excel怎么添加行列 excel表格添加行列,如有不对的地方欢迎指正! 总结: 第一种方法,1、打开需要添加行的表格。2、以张三为例添加行,选中

  • pdf保存成图片格式 免费将图片转为pdf的软件推荐

    pdf保存成图片格式 免费将图片转为pdf的软件推荐

    IT袋网为你介绍pdf保存成图片格式和免费将图片转为pdf的软件推荐的相关话题,一起跟随小编看看吧! 有人看到这个问题可能会说“:不就是截个图的事情吗,看起来也不是很难的样子。” 但

  • excel有单位怎么求和 excel有kg 有g怎么求和

    excel有单位怎么求和 excel有kg 有g怎么求和

    本文为你详解excel有kg,有g怎么求和方面的讲解,关于excel有单位怎么求和 excel有kg,有g怎么求和,一起来了解了解吧。 图文步骤: 1、打开excel表格,输入下图中的内容。 2、将kg的数据换算成g,

  • wps怎样在图片上加水印 wps加水印文字在图片上方法

    wps怎样在图片上加水印 wps加水印文字在图片上方法

    正文核心介绍:wps加水印文字在图片上方法的相关话题,关于wps加水印文字在图片上方法 或者 wps怎样在图片上加水印,请看下面详细的介绍。 我们如果想要保护自己的图片版权,就可以将水