SpringBoot+Thymeleaf实现生成PDF文档

2023-05-16 0 2,092

目录

前言

温馨提示:本博客使用Thymeleaf模板引擎实现PDF打印仅供参考:

在阅读该博客之前,先要了解一下Thymeleaf模板引擎,因为是使用Thymeleaf模板引擎实现的PDF打印的,

Thymeleaf是一个现代的服务器端 Java 模板引擎,适用于 Web 和独立环境。

Thymeleaf 的主要目标是为您的开发工作流程带来优雅的自然模板——HTML可以在浏览器中正确显示,也可以用作静态原型,从而在开发团队中实现更强大的协作。

借助 Spring Framework 的模块、与您最喜欢的工具的大量集成以及插入您自己的功能的能力,Thymeleaf 是现代 HTML5 JVM Web 开发的理想选择——尽管它可以做的更多。

不了解小伙伴可以去Thymeleaf官网查看,有更详细的讲解。

接下来就不一一介绍了,直接上代码。

一、引入依赖

1.Thymeleaf,生成PDF相关依赖

1.1 以下依赖为必要依赖,一个都不能少,依赖version可以根基实际情况使用相关的依赖版本。

SpringBoot+Thymeleaf实现生成PDF文档

二、application.yml配置

1.yml配置文件

yml配置文件使用配置thymeleaf模板路径(示例):

SpringBoot+Thymeleaf实现生成PDF文档

以上相关为基础且必须配置的内容,接下来继续讲解thymeleaf引擎需要生成PDF的相关配置。

三、PDF相关配置

1.PDF配置代码(如下):

package com.cy.xgsm.configuration;

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.layout.font.FontProvider;
import com.cy.xgsm.controller.PrintPdfController;

/**
 * 
 * @author Dylan
 * PDF相关配置
 */
@Configuration
public class PdfConfiguration {
	
	private static final Logger log = LoggerFactory.getLogger(PdfConfiguration.class);
	
	@Bean
	public FontProvider getFontProvider() throws URISyntaxException, IOException {
		FontProvider provider = new DefaultFontProvider(true, true, false);
		byte[] bs = null;
		//SIMSUN.TTC为字体
		try (InputStream in = PrintPdfController.class.getClassLoader().getResourceAsStream(\"font/SIMSUN.TTC\")) {
			bs = IOUtils.toByteArray(in);
		}		
		PdfFont pdfFont = PdfFontFactory.createTtcFont(bs, 1, PdfEncodings.IDENTITY_H, false, true);
		provider.addFont(pdfFont.getFontProgram());
		return provider;
	}
	
	@Bean
	public ConverterProperties converterProperties(FontProvider fontProvider, Configuration config) {
		ConverterProperties cp = new ConverterProperties();
		cp.setBaseUri(config.getPdfUrl());
		try {
			cp.setFontProvider(fontProvider);
		} catch (Exception e) {
			log.error(\"打印PDF时未能添加字体\", e);
		}
		return cp;
	}
	
}

注意PDF配置需要添加打印PDF字体,SIMSUN.TTC为打印需要的字体,但是也可以是其他的

四、Controller

1.以上所有的相关配置信息都配置完了,接下来就可以写Api接口了

package com.cy.xgsm.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.cy.xgsm.common.Result;
import com.cy.xgsm.model.OrderInfo;
import com.cy.xgsm.service.OrderInfoService;

/**
 * 打印PDF 控制接入层
 * 
 * @author Dylan
 *
 */
@Controller
@RequestMapping(\"print\")
public class PrintPdfController {
	
    private static final Logger log = LoggerFactory.getLogger(PrintPdfController.class);
    
	@Autowired
	private OrderInfoService service;
	//thymeleaf模板引擎
    @Autowired
    TemplateEngine templateEngine;
	//html转换成pdf需要使用ConverterProperties
    @Autowired
    ConverterProperties converterProperties;    
	
    @GetMapping(\"order/{orderId}.pdf\")
	public void orderPdf(@PathVariable Long orderId, HttpServletResponse resp) throws IOException {
		Result<OrderInfo> result = service.selectByPrimaryKey(orderId);
		if (!result.isComplete()) {
            resp.sendError(404, \"订单ID不存在\");
        }
        Context context = new Context();
        context.setVariable(\"order\", result.getData());
		///html/pdf/order-template为打印模板纸张路径
        processPdf(context, \"/html/pdf/order-template\", result.getData().getKddh(), resp);
		
	}

	/**
	 * 调用生成PDF
	 * @param context 上下文
	 * @param template 模板文件
	 * @param filename 文件名
	 * @param resp
	 */
	private void processPdf(Context context, String template, String filename, HttpServletResponse resp) throws IOException {
        log.info(\"生成PDF:\" + filename);
        String html = templateEngine.process(template, context);
        String filenameEncoded = URLEncoder.encode(filename, \"utf-8\");
        resp.setContentType(\"application/pdf\");
        resp.setHeader(\"Content-Disposition\", \"filename=\" + filenameEncoded + \".pdf\");
        try (OutputStream out = resp.getOutputStream()) {
            PdfDocument doc = new PdfDocument(new PdfWriter(out));
			//打印使用什么什么纸张可根据实际情况,我这里默认使用A4
            doc.setDefaultPageSize(PageSize.A4.rotate());
            HtmlConverter.convertToPdf(html, doc, converterProperties);
        }
		
	}

}

1.请求接口报错解决方式:

如果在请求接口的时候发生以下错误信息是打印模板的路径错误了。

SpringBoot+Thymeleaf实现生成PDF文档

解决该错误需在你的yml配置thymeleaf路径即可,不懂怎么配置请往上看第二点application.yml配置,可按照application.yml复制上去即可解决。

五、生成PDF文件响应效果

SpringBoot+Thymeleaf实现生成PDF文档

点击Save to a file保存,响应结果数据均为测试数据,仅供参考。

SpringBoot+Thymeleaf实现生成PDF文档

资源下载此资源下载价格为1小猪币,终身VIP免费,请先
由于本站资源来源于互联网,以研究交流为目的,所有仅供大家参考、学习,不存在任何商业目的与商业用途,如资源存在BUG以及其他任何问题,请自行解决,本站不提供技术服务! 由于资源为虚拟可复制性,下载后不予退积分和退款,谢谢您的支持!如遇到失效或错误的下载链接请联系客服QQ:442469558

:本文采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可, 转载请附上原文出处链接。
1、本站提供的源码不保证资源的完整性以及安全性,不附带任何技术服务!
2、本站提供的模板、软件工具等其他资源,均不包含技术服务,请大家谅解!
3、本站提供的资源仅供下载者参考学习,请勿用于任何商业用途,请24小时内删除!
4、如需商用,请购买正版,由于未及时购买正版发生的侵权行为,与本站无关。
5、本站部分资源存放于百度网盘或其他网盘中,请提前注册好百度网盘账号,下载安装百度网盘客户端或其他网盘客户端进行下载;
6、本站部分资源文件是经压缩后的,请下载后安装解压软件,推荐使用WinRAR和7-Zip解压软件。
7、如果本站提供的资源侵犯到了您的权益,请邮件联系: 442469558@qq.com 进行处理!

猪小侠源码-最新源码下载平台 Java教程 SpringBoot+Thymeleaf实现生成PDF文档 https://www.20zxx.cn/704870/xuexijiaocheng/javajc.html

猪小侠源码,优质资源分享网

常见问题
  • 本站所有资源版权均属于原作者所有,均只能用于参考学习,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担
查看详情
  • 最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,建议提前注册好百度网盘账号,使用百度网盘客户端下载
查看详情

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务