“ 本文主要介绍Java生成PDF”
如题,在日常的项目开发中,我们会遇到需要通过Java代码生成pdf,本文主要介绍的是通过velocity模板生产pdf。
我们利用springboot可以快速开发项目,因为本文是采用的eclipse作为开发工具,直接打开官网进行项目的配置下载。下载下来的基本结构是如下图:
接下来我们修改pom.xml文件,引入需要的相关包。
org.apache.velocity velocity 1.7 org.apache.velocity.tools velocity-tools 2.0-alpha1 org.xhtmlrenderer core-renderer R8 com.github.xiaoymin knife4j-spring-boot-starter 2.0.7
配置完后我们就可以进入到正题了,为了方便演示,我们不再进行数据库连接查数据操作,而是直接采用接口传入参数值进行动态的变化以实现不同的值的展示。
我们先创建User对象,用于接收我们的接口数据。
import java.util.Date;import org.springframework.format.annotation.DateTimeFormat;import io.swagger.annotations.ApiModel;import io.swagger.annotations.ApiModelProperty;@ApiModel(value = "用户信息")public class User {
@ApiModelProperty(value="用户姓名", position = 1, required = true, example = "木左") private String name; @ApiModelProperty(value="性别", position = 1, required = true, example = "1", notes = "性别静态字典 1 男 2 女", allowableValues = "1,2") private int sex; @ApiModelProperty(value = "手机号", position = 2, required = true, example = "15530651234") private String mobile; @ApiModelProperty(value = "地址", position = 3, required = true, example = "北京市昌平区XXXX") private String address; @ApiModelProperty(value = "注册时间", position = 4, required= true, example = "2020-12-27 10:49:50" ,notes ="格式 yyyy-MM-dd HH:mm:ss", dataType="Date") @DateTimeFormat(pattern="y