如何利用java实现生成PDF文件
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);
}
总结
到此这篇关于如何利用java实现生成PDF文件的文章就介绍到这了,更多相关java生成PDF文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
基于指针pointers和引用references的区别分析
本篇文章介绍了,基于指针pointers和引用references的区别分析。需要的朋友参考下2013-05-05
Java 中的FileReader和FileWriter源码分析_动力节点Java学院整理
本文给大家分享一段示例程序,通过示例代码可以看出FileReader是基于InputStreamReader实现的,FileWriter是基于OutputStreamWriter实现的,具体程序代码大家通过本文了解下吧2017-05-05
SpringBoot2.x 集成 Thymeleaf的详细教程
本文主要对SpringBoot2.x集成Thymeleaf及其常用语法进行简单总结,其中SpringBoot使用的2.4.5版本。对SpringBoot2.x 集成 Thymeleaf知识感兴趣的朋友跟随小编一起看看吧2021-07-07
IntelliJ IDEA cmd和idea Terminal查看java版本不一致的解决
原来win10电脑上安装的是jdk8的版本,因某些原因,现在想换成jdk7的版本,修改环境变量后,在cmd中执行 [java -version]命令,显示的是7的版本,遇到这样的问题如何解决呢?下面小编给大家分享IntelliJ IDEA cmd和idea Terminal查看java版本不一致的解决方案,一起看看吧2023-09-09
Spring Boot中的@EnableAutoConfiguration注解详解
这篇文章主要介绍了Spring Boot中的@EnableAutoConfiguration注解详解,Spring Boot是一个非常流行的Java框架,它可以快速创建基于Spring的应用程序。Spring Boot提供了许多自动配置功能,使得开发者可以非常容易地创建一个可运行的应用程序,需要的朋友可以参考下2023-08-08
SpringBoot通过注解监测Controller接口的代码示例
在Spring Boot中,度量指标(Metrics)是监控和诊断应用性能与行为的重要工具,Spring Boot通过集成Micrometer和Spring Boot Actuator,提供了强大的度量指标收集与暴露功能,本文介绍了SpringBoot通过注解监测Controller接口,需要的朋友可以参考下2024-07-07


最新评论