如何利用java实现生成PDF文件
作者:xhga 时间:2023-03-31 16:25:36
1.PDF文件简介
PDF是可移植文档格式,是一种电子文件格式,具有许多其他电子文档格式无法相比的优点。PDF文件格式可以将文字、字型、格式、颜色及独立于设备和分辨率的图形图像等封装在一个文件中。该格式文件还可以包含超文本链接、声音和动态影像等电子信息,支持特长文件,集成度和安全可靠性都较高。在系统开发中通常用来生成比较正式的报告或者合同类的电子文档。
2.生成PDF
2.1 基于freemarker框架实现HTML转PDF
2.1.1 引入jar包依赖:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf/html2pdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>4.0.3</version>
</dependency>
<!-- spring boot 项目请添加此依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- 非spring boot 项目请添加此依赖 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
2.1.2 创建html模板test_template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
<style>
body{font-family:SimSun;}
.title{align-content: center;text-align: center;}
.signature{float:right }
</style>
</head>
<body>
<div>
<h1 class="title">标题</h1>
<h4 class="title">副标题</h4>
<span>当前时间: ${date_time} </span>
<div class="signature">日期:${date}</div>
</div>
</body>
</html>
2.1.3 获取HTML内容
当HTML模板存放在系统文件夹
String templateDirectory = "D:\\"; // 系统文件夹路径 如: D:\
当HTML模板存放在项目resources/templates目录
ClassLoader classLoader = PdfUtilTest.class.getClassLoader();
URL resource = classLoader.getResource("templates");
String templateDirectory = resource.toURI().getPath();
示例代码:
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.layout.font.FontProvider;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class PdfUtilTest {
/**
* 获取模板内容
* @param templateDirectory 模板文件夹
* @param templateName 模板文件名
* @param paramMap 模板参数
* @return
* @throws Exception
*/
private 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();
}
public static void main(String[] args) throws Exception {
Map<String, Object> paramMap = new HashMap<>();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
paramMap.put("date_time", dateTimeFormatter.format(LocalDateTime.now()));
paramMap.put("date", dateTimeFormatter.format(LocalDateTime.now()).substring(0, 10));
ClassLoader classLoader = PdfUtilTest.class.getClassLoader();
URL resource = classLoader.getResource("templates");
String templateDirectory =resource.toURI().getPath();
String templateContent = PdfUtilTest.getTemplateContent(templateDirectory, "test_template.html", paramMap);
System.out.println(templateContent);
}
}
2.1.4 生成PDF文档
示例代码:
/**
* 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();
}
public static void main(String[] args) throws Exception {
Map<String, Object> paramMap = new HashMap<>();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
paramMap.put("date_time", dateTimeFormatter.format(LocalDateTime.now()));
paramMap.put("date", dateTimeFormatter.format(LocalDateTime.now()).substring(0, 10));
String outPath = "D:\\A.pdf";
String templateDirectory = "D:\\";
String templateContent = PdfUtilTest.getTemplateContent(templateDirectory, "test_template.html", paramMap);
PdfUtilTest.html2Pdf(templateContent, outPath);
}
来源:https://blog.csdn.net/qq_37751454/article/details/109266141
标签:java,生成,pdf文档
0
投稿
猜你喜欢
利用spring aop实现动态代理
2022-02-02 16:50:25
java 如何给对象中的包装类设置默认值
2022-02-09 21:04:08
用Newtonsoft将json串转为对象的方法(详解)
2022-12-31 23:32:21
一文带你了解Java万物之基之Object类
2023-10-09 01:58:28
elasticsearch分布式及数据的功能源码分析
2023-08-11 06:31:26
Java编程泛型限定代码分享
2023-11-09 17:46:32
springboot整合token的实现代码
2023-11-10 19:02:03
解决Mybatis 大数据量的批量insert问题
2023-09-08 13:59:40
java 图片验证码的实现代码
2023-11-09 13:33:52
eclipse 联想功能设置技巧
2023-03-18 04:11:39
JavaScript 与 Java 区别介绍 学java怎么样
2023-11-25 12:23:49
spring data jpa如何使用自定义repository实现类
2023-05-31 07:41:17
Java 实战项目之在线点餐系统的实现流程
2022-08-05 04:11:35
PageHelper在springboot+mybatis框架中的使用步骤及原理解析
2023-07-28 21:40:09
Android图片处理工具类BitmapUtils
2022-12-28 05:23:39
Apache Shrio安全框架实现原理及实例详解
2023-07-27 19:47:59
java 中设计模式(值对象)的实例详解
2021-12-27 14:15:08
Android 登录Web 时对cookie 处理
2022-05-08 20:16:11
通过实例讲解springboot整合WebSocket
2023-03-07 07:02:03
c语言中十六进制转二进制显示的实现方法
2023-12-17 23:21:44