利用Velocity在springboot中生成pdf

 <!--pdf相关-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>html2pdf</artifactId>
            <version>4.0.3</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>font-asian</artifactId>
            <version>7.2.3</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.4</version>
        </dependency>

第一步:PDF工具类

package com.demo.common.util;
 
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工具
 *
 *
 */
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);
        }
    }
 
}

第二步:在resources下pdf.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
</head>
<style type="text/css">
    table {
        width: 300px;
        height: 300px;
        text-align: center;
        border: 1px;
        cellSpacing: 0;
    }

    .a {
        background: rgba(202, 236, 241, 0.85);
    }
    table,tr, th, td {
        border: solid 1px #edf0f5;
    }
    table{
        width: 100%;
        height: 100%;
        margin: 0 auto;
        border: 1px;
        cellSpacing: 0px;
        border-collapse: collapse;
        border-spacing: 0;
    }

</style>
<body>
<center>
    <div class="content">
        <h1>个人资料</h1>
        <table>
            <tr>
                <td class="a">用户名</td>
                <td>$!{username}</td>
                <td class="a">昵称</td>
                <td>$!{nickname}</td>
<!--                <td rowspan="1" colspan="1">-->
                <td colspan="2">
                    <img width=100px height=100px src="$!{avatarUrl}">
                </td>
            </tr>
            <tr>
                <td class="a">性别</td>
                <td>
                    #if($!{sex}==0)
                    男
                    #else
                    女
                    #end
                </td>
                <td class="a">邮箱</td>
                <td>$!{email}</td>
                <td class="a">手机号</td>
                <td>$!{phonenumber}</td>
            </tr>

            <tr>
                <td colspan="6" class="a">工作经历</td>
            </tr>
            <tr>
                <td>开始时间</td>
                <td>结束时间</td>
                <td>公司名称</td>
                <td>地点</td>
                <td>岗位</td>
                <td>离职原因</td>
            </tr>
            #foreach($item in $list)
            <tr>
                <td>$item.a</td>
                <td>$item.b</td>
                <td>$item.c</td>
                <td>$item.d</td>
                <td>$item.e</td>
                <td>$item.f</td>
            </tr>
            #end

            <tr>
                <td colspan="6" class="a">图片</td>
            </tr>
            #foreach($item in $pictures)
            <tr>
                <td width="100%" colspan="6">
                    <img width=200px height=100px  src="$item.picture"/>
                </td>
            </tr>
            #end
        </table>


    </div>
</center>
</body>
</html>

 第三步:controller层

package com.demo.controller;
 
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.URLUtil;
import com.demo.common.util.PdfUtil;
import com.demo.pojo.User;
import com.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.VelocityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * PDF生成Controller
 */
@Slf4j
@Controller
@RequestMapping("/pdf")
public class PDFController {
    @Autowired
    private UserService userService;

    @RequestMapping("/get/{userId}")
    public void get(HttpServletResponse response,@PathVariable Integer userId) {
        response.reset();
        response.setContentType("application/pdf");
        String filename = System.currentTimeMillis() + ".pdf";
        response.addHeader("Content-Disposition", "inline; filename=" + URLUtil.encode(filename, CharsetUtil.CHARSET_UTF_8));

        User user = userService.selectUserById(userId);

        VelocityContext context = new VelocityContext();

        context.put("username", user.getUsername());
        context.put("nickname", user.getNickname());
        context.put("avatarUrl", user.getAvatar());
        context.put("sex", user.getSex());
        context.put("email", user.getEmail());
        context.put("phonenumber", user.getPhonenumber());

        //工作经历
        List<Map<String, Object>> list = new ArrayList<>();
 
        Map<String, Object> work1 = new HashMap<>();
        work1.put("a", "2021-01-10");
        work1.put("b",  "2021-06-10");
        work1.put("c", "娃哈哈公司");
        work1.put("d", "江苏南京");
        work1.put("e", "主管");
        work1.put("f", "长期加班,身体跟不上");
        list.add(work1);
        Map<String, Object> work2 = new HashMap<>();
        work2.put("a", "2022-06-10");
        work2.put("b",  "2023-10-10");
        work2.put("c","KFC公司");
        work2.put("d", "江苏南京");
        work2.put("e", "销售经理");
        work2.put("f", "换个城市发展");
        list.add(work2);

        context.put("list", list);
 
        //图片处理
        List<Map<String, String>> pictures = new ArrayList<>();
        Map<String, String> map1 = new HashMap<>();
        map1.put("picture", "http://127.0.0.1:8081/images/80820a667f1443b8bd6debb35128b0df.png");
        Map<String, String> map2 = new HashMap<>();
        map2.put("picture", "http://127.0.0.1:8081/images/f202c760a2714de394b60a7cddaca35d.png");
        pictures.add(map1);
        pictures.add(map2);
        context.put("pictures", pictures);
 
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            PdfUtil.pdfFile(context, "pdf.html", outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

关于从数据库中获取数据一些相关代码就不展示,pdf效果图展示:

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值