<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>4.0.3</version>
</dependency>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
<style>
body{
font-size: 15px;
}
.title{
text-align: center;
}
.content{
margin:0 auto;
width: 400px;
}
.content .text{
text-indent: 2em;
}
.content .datetime{
text-align: right;
}
</style>
</head>
<body>
<div>
<div class="view">
<h2 class="title">自我介绍</h2>
<div class="content">
<p class="text">
大家好,我叫${person.personName},我今年${person.personAge},我是个${person.personGender},
我的职业是${person.personVocation},我目前住在${person.address},我在性格方面${person.personalityDesc}。
</p>
<p class="datetime">${person.createTime}</p>
</div>
</div>
</div>
</body>
</html>
在准备一个PDFUtil的工具类
PDFUtil工具类
public class PdfUtil {
@Autowired
private Configuration configuration;
/**
* 获取模板内容
* @param templateDirectory 模板文件夹
* @param templateName 模板文件名
* @param paramMap 模板参数
* @return
* @throws Exception
*/
public static String getTemplateContent(String templateDirectory, String templateName, Map<String, Object> paramMap) throws Exception {
Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
try {
configuration.setDirectoryForTemplateLoading(new File(templateDirectory));
} catch (Exception e) {
System.out.println("-- exception --");
}
Writer out = new StringWriter();
Template template = configuration.getTemplate(templateName,"UTF-8");
template.process(paramMap, out);
out.flush();
out.close();
return out.toString();
}
/**
* HTML 转 PDF
* @param content html内容
* @param outPath 输出pdf路径
* @return 是否创建成功
*/
public static boolean html2Pdf(String content, String outPath) {
try {
ConverterProperties converterProperties = new ConverterProperties();
converterProperties.setCharset("UTF-8");
FontProvider fontProvider = new FontProvider();
fontProvider.addSystemFonts();
converterProperties.setFontProvider(fontProvider);
HtmlConverter.convertToPdf(content, new FileOutputStream(outPath), converterProperties);
} catch (Exception e) {
log.error("生成模板内容失败,{}",e);
return false;
}
return true;
}
/**
* HTML 转 PDF
* @param content html内容
* @return PDF字节数组
*/
public static byte[] html2Pdf(String content) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
ConverterProperties converterProperties = new ConverterProperties();
converterProperties.setCharset("UTF-8");
FontProvider fontProvider = new FontProvider();
fontProvider.addSystemFonts();
converterProperties.setFontProvider(fontProvider);
HtmlConverter.convertToPdf(content,outputStream,converterProperties);
} catch (Exception e) {
log.error("生成 PDF 失败,{}",e);
}
return outputStream.toByteArray();
}
}
Bean类
```java
@Data
public class PersonIntroduce {
//名称
private String personName ;
//年龄
private Integer personAge ;
//性格描述
private String personalityDesc;
//性别
private String personGender;
//职业
private String personVocation;
//现居地址
private String address;
//创建时间
private String createTime;
}
Controller层代码
@Controller
public class PersonIntroduceController {
@Autowired
private PersonIntroduceService personIntroduceService;
@GetMapping("/exPdf")
@ResponseBody
public void exPdfPersonIntroduce(HttpServletRequest request , HttpServletResponse response) throws TemplateException, IOException {
PersonIntroduce personIntroduce = new PersonIntroduce();
personIntroduce.setPersonName("小刘");
personIntroduce.setAddress("北京朝阳区");
personIntroduce.setPersonAge(24);
personIntroduce.setPersonGender("男生");
personIntroduce.setPersonalityDesc("其实我也不是很清楚");
personIntroduce.setPersonVocation("Java后端开发");
personIntroduceService.exPersonIntroduce(personIntroduce , request , response);
}
}
Service业务层代码:
注意:建议使用这种方式,之前我在项目开发的过程中,使用了PdUtil.class.ClassLoader()这种方式去定位exPdf.html,在线下(开发环境)是可以使用的,但是部署到服务器的时候就出现了文件找不到的情况,因为上述这种方式他是使用的磁盘绝对路径查找的。使用freeMarkerConfigurer.getConfiguration().getTemplate(“exPdf.html”);来定位就不会出现这种问题。文章来源:https://www.toymoban.com/news/detail-670670.html
@Service
public class PersonIntroduceServiceImpl implements PersonIntroduceService {
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
/**
* PDF导出类
* @param personIntroduce
*/
public void exPersonIntroduce(PersonIntroduce personIntroduce , HttpServletRequest request, HttpServletResponse response) throws IOException, TemplateException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
Map<String, Object> paramMap = new HashMap<>();
personIntroduce.setCreateTime(sdf.format(new Date()));
paramMap.put("person" , personIntroduce);
Writer out = new StringWriter();
//获取模板地址
Template template = freeMarkerConfigurer.getConfiguration().getTemplate("exPdf.html");
template.process(paramMap, out);
out.flush();
out.close();
String templateContent = out.toString();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/pdf");
String fileName =personIntroduce.getPersonName() + "-个人介绍-" + sdf.format(new Date());
response.setHeader("Content-Disposition", "filename=" + new String(fileName.getBytes(), "iso8859-1"));
byte[] resources = PdfUtil.html2Pdf(templateContent);
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(resources);
outputStream.close();
}
}
项目结构:
文章来源地址https://www.toymoban.com/news/detail-670670.html
到了这里,关于2023最新SpringBoot导出PDF方式(模板方式)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!