Thymeleaf企业级真实应用:将HTML界面数据转换为PDF输出

目录

目录

1.Thymeleaf说明

1.1什么是Thymeleaf

1.2Thymeleaf具有特点

 2.将HTML界面数据转换为PDF输出逻辑说明

2.1中心思想

2.2操作说明 

2.3具体步骤

3.具体实现 

 3.1添加依赖

 3.2定义HTML模板

 3.3html 模板渲染工具

HtmlTemplate

 3.4 读取html 模板渲染结果并且转换为Base64字符串

字体路径 

 PdfUtils 

 Base64Utils

 3.4.1 库:ITextRenderer说明

 3.4.2 类:ITextFontResolver说明

3.4.3转换为Base64总结说明

 3.5 base64转成PDF后返回当前pdf的路径,本地下载

3.5.1 ByteArrayOutputStream说明

 3.5.2 方法整合使用

3.6 base64转成PDF后,调用接口,触发浏览器下载

 3.6.1 方法整合使用

4.几个html报告模板

Template1: 

Template2: 


 Thymeleaf模板引擎使用,Java又一神器

1.Thymeleaf说明

1.1什么是Thymeleaf

Thymeleaf是一种现代化的服务器端Java模板引擎可以用于Web和独立环境中的HTML、XML、JavaScript、CSS和文本。在实际开发中,Thymeleaf可以用于生成动态的HTML页面,支持将数据与模板进行绑定,生成最终的HTML内容。它是一个开源的软件,采用Apache许可证2.0进行发布。

1.2Thymeleaf具有特点

与其他服务器端Java模板引擎相比,Thymeleaf具有以下特点:

  • 语法简单易懂,支持自然的HTML标签
  • 支持HTML5的规范和特性
  • 支持CSS样式的绑定和操作
  • 支持表达式语言(Expression Language,简称EL)和Spring表达式语言(Spring Expression Language,简称SpEL)
  • 支持标准和Spring MVC的多种模板渲染方式
  • 支持多种模板缓存策略
  • 支持可扩展的引擎架构

在实际开发中,Thymeleaf可以用于生成动态的HTML页面,支持将数据与模板进行绑定,生成最终的HTML内容。它可以作为Web应用程序的模板引擎,也可以作为其他应用程序的模板引擎。由于其简单易用的语法和强大的功能,Thymeleaf已经成为Java领域中最受欢迎的模板引擎之一。

 2.将HTML界面数据转换为PDF输出逻辑说明

2.1中心思想

使用模板引擎的模板文件和数据模型。模板文件定义了最终输出的PDF页面的结构和样式,而数据模型则提供了模板中要填充的动态数据。

具体来说,Thymeleaf使用Java对象作为数据模型,可以通过Spring的控制器将数据注入到数据模型中。然后,Thymeleaf将数据模型与模板文件结合起来,生成HTML内容。最后,使用PDF生成库将HTML内容转换为PDF输出。

2.2操作说明 

在实现PDF输出功能时,可以使用Spring Boot提供的spring-boot-starter-thymeleaf依赖,该依赖包含了Thymeleaf、PDF生成库以及其他必需的依赖项。可以在控制器中使用Thymeleaf的TemplateEngine对象将数据模型和模板文件合并,生成HTML内容。然后,可以使用PDF生成库将HTML内容转换为PDF格式。

需要注意的是,PDF输出可能需要一些特定的CSS样式和HTML标记,以便正确呈现和格式化PDF页面。因此,在生成PDF输出之前,可能需要对模板文件进行调整和优化,以确保输出的PDF页面具有所需的外观和布局。

2.3具体步骤

  1. 定义HTML模板,需要输出的数据以HTML格式创建一个模板,生成.HTML文件
  2. 引入Thymeleaf中TemplateEngine-》生成文本输出的Java模板引擎框架、Context-》Web应用程序的上下文对象。生成html 模板渲染工具。处理上边我们定义的模板。得到一个String类的结果
  3. 读取这个结果byte[],将byte数组 转换为 Base64字符串
  4. 最后将Base64字符串转换为PDF格式的数据,输出路径
     

3.具体实现 

 3.1添加依赖

 <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.8.RELEASE</version>
  </parent>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

 3.2定义HTML模板

<html>
    <head>
        <title>Hello World!</title>
    </head>
    <body>
        <h1>Hello, ${name}!</h1>
        <p>You are ${age} years old.</p>
    </body>
</html>

 3.3html 模板渲染工具

HtmlTemplate
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import java.util.Map;


/**
 * html 模板渲染工具
 */
@Component
public class HtmlTemplate {
    @Resource
    private TemplateEngine templateEngine;

    /**
     * 使用 Thymeleaf 渲染 HTML
     * @param template HTML模板
     * @param params 参数
     * @return
     * @throws Exception
     */
    public String render(String template, Map<String,Object> params) throws Exception {
        // 创建模板上下文
        Context context = new Context();
        // 设置变量
        context.setVariables(params);
        //将数据填充到模板里,开始处理模板
        return templateEngine.process(template, context);
    }

}

 3.4 读取html 模板渲染结果并且转换为Base64字符串

字体路径 

 PdfUtils 
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.ByteArrayOutputStream;

public class PdfUtils {
   
    public static String getPdfBase64ByHtml(String html) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//构建字节输出流
        ITextRenderer renderer = new ITextRenderer();
        ITextFontResolver fontResolver = renderer.getFontResolver();
        //指定文件字体添加到PDF库,指定字体不作为内部字体,而是外部字体被加载
        fontResolver.addFont("pdf/font/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        renderer.setDocumentFromString(html);
        renderer.layout();
        renderer.createPDF(baos);
        return Base64Utils.encode(baos.toByteArray());
    }
}

在添加了字体文件后,可以使用setDocumentFromString()方法将HTML文档设置到渲染器中,并使用layout()方法对文档进行排版布局。接下来,使用createPDF()方法将文档渲染为PDF,并输出到输出流中。

注意,在添加字体文件时,需要确保字体文件的路径正确,并且字体文件能够被读取到。此外,还需要确保字体文件的格式正确,可以使用BaseFont.IDENTITY_H指定字体编码,使用BaseFont.NOT_EMBEDDED指定字体文件是否嵌入到PDF文件中。

 Base64Utils

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
 * Base64 转换工具
 */
public class Base64Utils {

    /**
     * byte数组 转换为 Base64字符串
     */
    public static String encode(byte[] data) {
        return new BASE64Encoder().encode(data);
    }

    /**
     * Base64字符串 转换为 byte数组
     */
    public static byte[] decode(String base64) {
        try {
            return new BASE64Decoder().decodeBuffer(base64);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    /**
     * 把文件内容编码为 Base64字符串, 只能编码小文件(例如文本、图片等)
     */
    public static String encodeFile(File file) throws Exception {
        InputStream in = null;
        ByteArrayOutputStream bytesOut = null;

        try {
            in = new FileInputStream(file);
            bytesOut = new ByteArrayOutputStream((int) file.length());

            byte[] buf = new byte[1024];
            int len = -1;

            while ((len = in.read(buf)) != -1) {
                bytesOut.write(buf, 0, len);
            }
            bytesOut.flush();

            return encode(bytesOut.toByteArray());

        } finally {
            close(in);
            close(bytesOut);
        }
    }

    /**
     * 把 Base64字符串 转换为 byte数组, 保存到指定文件
     */
    public static void decodeFile(String base64, File file) throws Exception {
        OutputStream fileOut = null;
        try {
            fileOut = new FileOutputStream(file);
      
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Recently 祝祝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值