spring boot 生成PDF模板文件

spring boot 生成PDF模板文件

码农世界 2024-06-04 后端 93 次浏览 0个评论

1、主要目录

spring boot 生成PDF模板文件

2、maven依赖


        
            cn.hutool
            hutool-all
            5.7.19
        
        
            com.alibaba
            fastjson
            1.2.76
        
        
        
            org.apache.velocity
            velocity
            1.7
        
        
            com.itextpdf
            html2pdf
            4.0.3
        
        
            com.itextpdf
            font-asian
            7.2.3
        

3、新建一个demo.html静态文件,后续导出模板就是按照此文件进行的




    


    
    
    

模板pdf

表1

姓名 $!{name}
性别 #if($!{gender}==1) 男 #else 女 #end
出生日期 $!{birthDate} 联系方式 $!{phone}

双重For循环取值

表2

#foreach($item in $eduList) #foreach($result in $item.itemList) #end #end
学历 学科 分数
$item.name
$velocityCount、$result.subject 60) #else #end>$result.num

4、新建PdfUtil工具类

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
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 org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import java.io.OutputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
/**
 * PDF工具
 *
 * @author ppp
 * @date 2022/8/5
 */
public class PdfUtil {
    static {
        // Velocity初始化
        Velocity.setProperty(RuntimeConstants.OUTPUT_ENCODING, StandardCharsets.UTF_8);
        Velocity.setProperty(RuntimeConstants.INPUT_ENCODING, StandardCharsets.UTF_8);
        Velocity.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        Velocity.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        Velocity.init();
    }
    /**
     * 据模板生成pfd格式文件
     *
     * @param context      上下文对象
     * @param template     pdf模板
     * @param outputStream 生成ofd文件输出流
     */
    public static void pdfFile(Context context, String template, OutputStream outputStream) {
        try (PdfWriter pdfWriter = new PdfWriter(outputStream)) {
            PdfDocument pdfDocument = new PdfDocument(pdfWriter);
            pdfDocument.setDefaultPageSize(PageSize.A4);
            ConverterProperties properties = new ConverterProperties();
            FontProvider fontProvider = new FontProvider();
            // 字体设置,解决中文不显示问题
            PdfFont sysFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H");
            fontProvider.addFont(sysFont.getFontProgram(), "UniGB-UCS2-H");
            properties.setFontProvider(fontProvider);
            Template pfdTemplate = Velocity.getTemplate(template, "UTF-8");
            StringWriter writer = new StringWriter();
            pfdTemplate.merge(context, writer);
            HtmlConverter.convertToPdf(writer.toString(), pdfDocument, properties);
            pdfDocument.close();
        } catch (Exception e) {
            throw new RuntimeException("PFD文件生成失败", e);
        }
    }
}

5、Controller接口测试,也可以根据业务来分层service

package com.example.springboot3.controller;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.URLUtil;
import com.example.springboot3.utils.PdfUtil;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.velocity.VelocityContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;
@RestController
@RequestMapping("/velocity")
public class PdfController {
    @GetMapping("/getPdf")
    public void get(HttpServletResponse response){
        response.reset();
        response.setContentType("application/pdf");
        String filename = System.currentTimeMillis()+".pdf";
        response.addHeader("Content-Disposition", "inline; filename=" + URLUtil.encode(filename, CharsetUtil.CHARSET_UTF_8));
        VelocityContext context = new VelocityContext();
        context.put("name", "彭也行");
        context.put("gender", 1);
        context.put("birthDate", DateUtil.formatDateTime(new Date()));
        context.put("phone", "13666666666");
        List> eduList = new ArrayList<>();
        // 小学
        Map primarySchoolMap = new HashMap<>();
        primarySchoolMap.put("name", "小学");
        List> scoreList = new ArrayList<>();
        // 语文成绩
        Map chineseScore = new HashMap<>();
        chineseScore.put("subject", "语文");
        chineseScore.put("num", 60);
        // 数学成绩
        Map mathScore = new HashMap<>();
        mathScore.put("subject", "数学");
        mathScore.put("num", 99);
        scoreList.add(chineseScore);
        scoreList.add(mathScore);
        primarySchoolMap.put("itemList", scoreList);
        primarySchoolMap.put("size", scoreList.size());
        // 初中
        Map middleSchoolMap = new HashMap<>();
        middleSchoolMap.put("name", "初中");
        List> middleScoreList = new ArrayList<>();
        // 语文成绩
        Map middleChineseScore = new HashMap<>();
        middleChineseScore.put("subject", "语文");
        middleChineseScore.put("num", 60);
        // 数学成绩
        Map middleMathScore = new HashMap<>();
        middleMathScore.put("subject", "数学");
        middleMathScore.put("num", 99);
        // 英语
        Map middleEnScore = new HashMap<>();
        middleEnScore.put("subject", "英语");
        middleEnScore.put("num", 55);
        middleScoreList.add(middleChineseScore);
        middleScoreList.add(middleMathScore);
        middleScoreList.add(middleEnScore);
        middleScoreList.add(middleEnScore);
        middleScoreList.add(middleEnScore);
        middleScoreList.add(middleEnScore);
        middleScoreList.add(middleEnScore);
        middleScoreList.add(middleEnScore);
        middleSchoolMap.put("itemList", middleScoreList);
        middleSchoolMap.put("size", middleScoreList.size());
        eduList.add(primarySchoolMap);
        eduList.add(middleSchoolMap);
        context.put("eduList", eduList);
        try(ServletOutputStream outputStream = response.getOutputStream()){
            PdfUtil.pdfFile(context, "static/demo.html", outputStream);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

6、调用接口浏览器预览

spring boot 生成PDF模板文件

转载请注明来自码农世界,本文标题:《spring boot 生成PDF模板文件》

百度分享代码,如果开启HTTPS请参考李洋个人博客
每一天,每一秒,你所做的决定都会改变你的人生!

发表评论

快捷回复:

评论列表 (暂无评论,93人围观)参与讨论

还没有评论,来说两句吧...

Top