如何利用java實現(xiàn)生成PDF文件
1.PDF文件簡介
PDF是可移植文檔格式,是一種電子文件格式,具有許多其他電子文檔格式無法相比的優(yōu)點。PDF文件格式可以將文字、字型、格式、顏色及獨立于設備和分辨率的圖形圖像等封裝在一個文件中。該格式文件還可以包含超文本鏈接、聲音和動態(tài)影像等電子信息,支持特長文件,集成度和安全可靠性都較高。在系統(tǒng)開發(fā)中通常用來生成比較正式的報告或者合同類的電子文檔。
2.生成PDF
2.1 基于freemarker框架實現(xiàn)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 項目請?zhí)砑哟艘蕾?-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- 非spring boot 項目請?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">標題</h1>
<h4 class="title">副標題</h4>
<span>當前時間: ${date_time} </span>
<div class="signature">日期:${date}</div>
</div>
</body>
</html>
2.1.3 獲取HTML內(nèi)容
當HTML模板存放在系統(tǒng)文件夾
String templateDirectory = "D:\\"; // 系統(tǒng)文件夾路徑 如: 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 {
/**
* 獲取模板內(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 轉 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 轉 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);
}
總結
到此這篇關于如何利用java實現(xiàn)生成PDF文件的文章就介紹到這了,更多相關java生成PDF文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
如何使用nexus在局域網(wǎng)內(nèi)搭建maven私服及idea的使用
這篇文章主要介紹了如何使用nexus在局域網(wǎng)內(nèi)搭建maven私服及idea的使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11
淺談java項目與javaweb項目導入jar包的區(qū)別
下面小編就為大家分享一篇淺談java項目與javaweb項目導入jar包的區(qū)別,具有很好的參考價值。希望對大家有所幫助。一起跟隨小編過來看看吧2017-11-11
AbstractQueuedSynchronizer內(nèi)部類Node使用講解
這篇文章主要為大家介紹了AbstractQueuedSynchronizer內(nèi)部類Node使用講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-07-07
SpringBoot使用JavaMailSender實現(xiàn)發(fā)送郵件
JavaMailSender是Spring Framework中的一個接口,用于發(fā)送電子郵件,本文主要為大家詳細介紹了SpringBoot如何使用JavaMailSender實現(xiàn)發(fā)送郵件,需要的可以參考下2023-12-12

