如何利用java实现生成PDF文件
作者:xhga 发布时间:2023-03-31 16:25:36
标签: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);
}
来源:https://blog.csdn.net/qq_37751454/article/details/109266141


猜你喜欢
- 1. 人机对战要增添一个人机对战的模块, 最大的难点就是如何让人机知道下在什么位置是最好的, 不仅要具备进攻的能力, 还需要具备防守的能力.
- 首先对Servlet上传文件的简单理解此前,Servlet本身没有对文件上传提供直接的支持,一般需要使用第三方框架来实现,这样就比较麻烦不过
- 目录环境依赖数据源方案一 使用 Spring Boot 默认配置方案二 手动创建脚本初始化使用 JdbcTemplate 操作实体对象DAO
- 水流波动的波形都是三角波,曲线是正余弦曲线,但是Android中没有提供绘制正余弦曲线的API,好在Pa
- 状态机机制状态机机制是一种常用的解决状态扭转问题的方法,通过定义状态以及状态之间的转移规则来控制状态的流转。对于订单系统,我们可以使用状态机
- 一、概述一共两个线程,一个线程生产产品,一个线程消费产品,使用同步代码块方法,同步两个线程。当产品没有时,通知生产者生产,生产者生产后,通知
- 一、导入和导出导入:通过解析excel表格中的数据,然后将数据放到一个集合中,接着通过对持久层操作,将数据插入到数据库中,再加载一下页面,从
- Java面向对象之猜拳游戏,供大家参考,具体内容如下1 要求与电脑进行猜拳并记录分数。2 Computer.java 源代码(电脑自动随机出
- 本文实例讲述了C#操作ftp类。分享给大家供大家参考。具体如下:using System;using System.Collections.
- 简介SPI(Service Provider Interface)是JDK内置的一种服务提供发现机制,可以用来启用框架扩展和替换组件,主要用
- 前言最学习动态规划思想的路上,遇见了‘分割回文串问题',如临大敌啊,题目听起来蛮简单,思考起来却也没那么容易,比解决问题更头疼的是如
- Windows系统启动Java程序会弹出黑窗口。黑窗口有几点不好。首先它不美观;其次容易误点导致程序关闭;但最让我匪夷所思的是:将鼠标光标选
- 一、时区的基本概念GMT(Greenwich Mean Time),即格林威治标准时,是东西经零度的地方。人们将地球人为的分为24等份,每一
- 上一篇博文说到了Shader的五个子类 - BitmapShader - LinearGradient - RadialGradient -
- 最近在开发的过程中,一个列表的查询,涉及到了多表的关联查询,由于持久层使用的是mongodb,对这个非关系型数据使用的不是很多,所以在实现此
- 我们知道,在java中,将一个非原型类型类型的对象引用,赋值给另一个对象的引用之后,这两个引用就指向了同一个对象,如:public clas
- 本文实例分析了Android动画之逐帧动画。分享给大家供大家参考,具体如下:在开始实例讲解之前,先引用官方文档中的一段话:Frame动画是一
- springboot加载yml文件获不到值今天使用spring boot读取yml文件,这种多层嵌套的竟然无法读取到(value注解spri
- android中提供了4中动画: AlphaAnimation 透明度动画效果 ScaleAnimation 缩放动画效果 Translat
- 本文实例为大家分享了Android短信验证服务的具体代码,供大家参考,具体内容如下package com.skiers.demo_learn