如何利用java實(shí)現(xiàn)生成PDF文件
1.PDF文件簡(jiǎn)介
PDF是可移植文檔格式,是一種電子文件格式,具有許多其他電子文檔格式無法相比的優(yōu)點(diǎn)。PDF文件格式可以將文字、字型、格式、顏色及獨(dú)立于設(shè)備和分辨率的圖形圖像等封裝在一個(gè)文件中。該格式文件還可以包含超文本鏈接、聲音和動(dòng)態(tài)影像等電子信息,支持特長(zhǎng)文件,集成度和安全可靠性都較高。在系統(tǒng)開發(fā)中通常用來生成比較正式的報(bào)告或者合同類的電子文檔。
2.生成PDF
2.1 基于freemarker框架實(shí)現(xiàn)HTML轉(zhuǎn)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 項(xiàng)目請(qǐng)?zhí)砑哟艘蕾?-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- 非spring boot 項(xiàng)目請(qǐng)?zhí)砑哟艘蕾?-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
2.1.2 創(chuàng)建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">標(biāo)題</h1>
<h4 class="title">副標(biāo)題</h4>
<span>當(dāng)前時(shí)間: ${date_time} </span>
<div class="signature">日期:${date}</div>
</div>
</body>
</html>
2.1.3 獲取HTML內(nèi)容
當(dāng)HTML模板存放在系統(tǒng)文件夾
String templateDirectory = "D:\\"; // 系統(tǒng)文件夾路徑 如: D:\
當(dāng)HTML模板存放在項(xiàng)目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 {
/**
* 獲取模板內(nèi)容
* @param templateDirectory 模板文件夾
* @param templateName 模板文件名
* @param paramMap 模板參數(shù)
* @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 轉(zhuǎn) PDF
* @param content html內(nèi)容
* @param outPath 輸出pdf路徑
* @return 是否創(chuàng)建成功
*/
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("生成模板內(nèi)容失敗,{}",e);
return false;
}
return true;
}
/**
* HTML 轉(zhuǎn) PDF
* @param content html內(nèi)容
* @return PDF字節(jié)數(shù)組
*/
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);
}
總結(jié)
到此這篇關(guān)于如何利用java實(shí)現(xiàn)生成PDF文件的文章就介紹到這了,更多相關(guān)java生成PDF文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用HttpClient調(diào)用接口的實(shí)例講解
下面小編就為大家?guī)硪黄褂肏ttpClient調(diào)用接口的實(shí)例講解。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-10-10
基于指針pointers和引用references的區(qū)別分析
本篇文章介紹了,基于指針pointers和引用references的區(qū)別分析。需要的朋友參考下2013-05-05
Java 中的FileReader和FileWriter源碼分析_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
本文給大家分享一段示例程序,通過示例代碼可以看出FileReader是基于InputStreamReader實(shí)現(xiàn)的,FileWriter是基于OutputStreamWriter實(shí)現(xiàn)的,具體程序代碼大家通過本文了解下吧2017-05-05
Java?Date(日期)對(duì)象進(jìn)行格式化的思路詳解
Date類是經(jīng)常會(huì)使用到的一個(gè)用來處理日期、時(shí)間的一個(gè)類。Date類是在java.util包下的Date類,這篇文章主要介紹了Java?Date(日期)對(duì)象如何進(jìn)行格式化呢,需要的朋友可以參考下2022-09-09
SpringBoot2.x 集成 Thymeleaf的詳細(xì)教程
本文主要對(duì)SpringBoot2.x集成Thymeleaf及其常用語法進(jìn)行簡(jiǎn)單總結(jié),其中SpringBoot使用的2.4.5版本。對(duì)SpringBoot2.x 集成 Thymeleaf知識(shí)感興趣的朋友跟隨小編一起看看吧2021-07-07
IntelliJ IDEA cmd和idea Terminal查看java版本不一致的解決
原來win10電腦上安裝的是jdk8的版本,因某些原因,現(xiàn)在想換成jdk7的版本,修改環(huán)境變量后,在cmd中執(zhí)行 [java -version]命令,顯示的是7的版本,遇到這樣的問題如何解決呢?下面小編給大家分享IntelliJ IDEA cmd和idea Terminal查看java版本不一致的解決方案,一起看看吧2023-09-09
Spring?Boot中的@EnableAutoConfiguration注解詳解
這篇文章主要介紹了Spring?Boot中的@EnableAutoConfiguration注解詳解,Spring?Boot是一個(gè)非常流行的Java框架,它可以快速創(chuàng)建基于Spring的應(yīng)用程序。Spring?Boot提供了許多自動(dòng)配置功能,使得開發(fā)者可以非常容易地創(chuàng)建一個(gè)可運(yùn)行的應(yīng)用程序,需要的朋友可以參考下2023-08-08
SpringBoot通過注解監(jiān)測(cè)Controller接口的代碼示例
在Spring Boot中,度量指標(biāo)(Metrics)是監(jiān)控和診斷應(yīng)用性能與行為的重要工具,Spring Boot通過集成Micrometer和Spring Boot Actuator,提供了強(qiáng)大的度量指標(biāo)收集與暴露功能,本文介紹了SpringBoot通過注解監(jiān)測(cè)Controller接口,需要的朋友可以參考下2024-07-07

