SpringBoot整合Thymeleaf实现PDF的生成

SpringBoot整合Thymeleaf实现PDF的生成

描述:最近在工作过程中发现需要生成pdf,在网上不断地摸索发现可以通过html文件转换成pdf文件。特此在这边记录下。

一、创建数据库

create table student
(id int not null auto_increment primary key ,
name varchar(20) null ,
age int null ,
sex varchar(20) null ,
address varchar(20) null );
insert into student(name,age,sex,address) values
('张三',18,'男','湖南'),
('李四',19,'女','湖北'),
('王五',18,'男','广东'),
('赵六',19,'女','广西');

在这里插入图片描述

二、添加依赖

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
		<version>2.6.7</version>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-thymeleaf</artifactId>
		<version>2.6.7</version>
	</dependency>
	<dependency>
		<groupId>org.xhtmlrenderer</groupId>
		<artifactId>flying-saucer-pdf</artifactId>
		<version>9.0.7</version>
	</dependency>
	<dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.24</version>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.5.2</version>
    </dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<version>2.6.7</version>
	</dependency>
</dependencies>

三、在yml中添加thymeleaf配置和数据库配置

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 123456
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    mode: HTML
    encoding: UTF-8
    servlet:
      content-type: text/html
    cache: false

四、编写HTML转PDF的工具类

import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class HtmlToPdf {

    public static void toPdf(String content, String path) throws DocumentException, FileNotFoundException {
        ITextRenderer renderer = new ITextRenderer();
        ITextFontResolver fontResolver = renderer.getFontResolver();
        try {
            //设置字体,否则不支持中文,在html中使用字体,html{ font-family: SimSun;}
            fontResolver.addFont("templates/SimSun.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } catch (IOException e) {
            e.printStackTrace();
        }
        renderer.setDocumentFromString(content);
        renderer.layout();
        renderer.createPDF(new FileOutputStream(new File(path)));
    }
}

五、编写html模板

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.w3.org/1999/xhtml" layout:decorator="layout">
<head lang="en">
    <title>Spring Boot Demo - PDF</title>
    <style>
        @page {
            size: 420mm 297mm; /*设置纸张大小:A4(210mm 297mm)、A3(297mm 420mm) 横向则反过来*/
            margin: 0.25in;
            padding: 1em;
            @bottom-center{
                content:"版权所有";
                font-family: SimSun;
                font-size: 12px;
                color:red;
            };
            @top-center { content: element(header) };
            @bottom-right{
                content:"第" counter(page) "页  共 " counter(pages) "页";
                font-family: SimSun;
                font-size: 12px;
                color:#000;
            };
        }
        body{font-family: 'SimSun'}
        td, th {
            font-style: normal;
            font-weight: normal;
            text-align: center;
        }

        tr {
            height: 40px;
        }

        .twoHead th {
            width: 6.25%;
            height: 40px;
            padding: 0 10px;
            font-size: 14px;
            font-weight: normal;
        }
        table {
            border: none;
            border-collapse: collapse;
            border-color: #D8DFE6;
        }
        table thead {
            background: #F3FDFF;
        }

    </style>
</head>
<!--这样配置不中文不会显示-->
<!--<body style="font-family: 宋体">-->
<body style="font-family: 'SimSun'">
<div class="table">
    <table border="1" cellspacing="0" cellpadding="10" width="100%">
        <thead>
        <tr class="twoHead">
            <th>ID</th>
            <th>名称</th>
            <th>年龄</th>
            <th>性别</th>
            <th>籍贯</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="demo : ${demoList}">
            <td th:text="${demo.id}"></td>
            <td th:text="${demo.name}"></td>
            <td th:text="${demo.age}"></td>
            <td th:text="${demo.sex}"></td>
            <td th:text="${demo.address}"></td>
        </tr>
        </tbody>
    </table>
</div>
</body>
</html>

六、编写实体类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    
    private Integer id;
    
    private String name;
    
    private Integer age;
    
    private String sex;
    
    private String address;
    
}

七、编写实现方法

@Mapper
@Repository
public interface StudentDao extends BaseMapper<Student> {
}
public interface StudentService {
    List<Student> findAll();
}
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;

    @Override
    public List<Student> findAll() {
        return studentDao.selectList(null);
    }
}

八、编写测试接口

@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private TemplateEngine templateEngine;

    @GetMapping("/index")
    public String index(HttpServletRequest request, HttpServletResponse response){
        WebContext context = new WebContext(request,response, request.getServletContext(),request.getLocale());
        List<Student> studentList = studentService.findAll();
        System.out.println(studentList);
        context.setVariable("demoList",studentList);
        try {
            String htmlContext = templateEngine.process("/pdfPage", context);
            HtmlToPdf.toPdf(htmlContext,"D:/student.pdf");
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.setAttribute("time", new Date());
        return "/pdfPage";
    }

}

九、在浏览器访问接口生成pdf文件

在这里插入图片描述

生成的PDF文件:

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 可以很方便的集成 Thymeleaf 模板引擎,下面是整合步骤: 1.添加 Thymeleaf 依赖 在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` 2.配置 Thymeleaf 模板 在 `src/main/resources/templates/` 目录下创建一个 thymeleaf 模板文件,例如 index.html: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Thymeleaf Demo</title> </head> <body> <h1 th:text="${message}">Hello World!</h1> </body> </html> ``` 其中 `${message}` 表示从后台传递过来的数据。 3.配置视图解析器 在 application.properties 或 application.yml 文件中添加以下配置: ```yaml spring: thymeleaf: cache: false prefix: classpath:/templates/ suffix: .html encoding: utf-8 ``` 其中: - `cache` 表示是否开启缓存 - `prefix` 表示模板文件所在目录 - `suffix` 表示模板文件后缀 - `encoding` 表示模板文件编码 4.在 Controller 中使用 Thymeleaf 在 Controller 中设置需要传递到前端的数据,并指定要返回的模板文件名: ```java @Controller public class DemoController { @GetMapping("/hello") public String hello(Model model) { model.addAttribute("message", "Hello, Thymeleaf!"); return "index"; } } ``` 其中: - `@Controller` 表示这是一个控制器 - `@GetMapping("/hello")` 表示处理 GET 请求,路径为 /hello - `Model` 用于存储需要传递到前端的数据 - `return "index"` 表示返回名为 index 的模板文件 5.运行项目 启动 Spring Boot 项目,访问 http://localhost:8080/hello 即可看到效果。 以上就是 Spring Boot 整合 Thymeleaf 的基本步骤,希望能对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值