PDF文件格式可以将文字、字型、格式、颜色及独立于设备和分辨率的图形图像等封装在一个文件中。本文实现将html页面转PDF。
生成pdf文件成功,但是文字对不上。当修改”GetHtmlContent“部分的编码之后,再次执行生成PDF文件即可完成正确的实现。
Edit Configurations
从这几点深入剖析和总结这个小项目:
该项目实现了解析一个模板html文件,将其转为pdf文件并输出到相应的目录中。
freemarker,FreeMarker是模板引擎,一个Java类库。
itextpdf,iText是一种生成PDF报表的Java类库,可以将Xml,Html文件转化为PDF文件。
类 XMLWorkerHelper,(用于解析 XHTML/CSS 或 XML 流到 PDF 的帮助器类)。
相关依赖
<dependency>
<groupId>com.itextpdfgroupId>
<artifactId>itextpdfartifactId>
<version>5.5.13.2version>
dependency>
<dependency>
<groupId>com.itextpdf.toolgroupId>
<artifactId>xmlworkerartifactId>
<version>5.5.13.2version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-freemarkerartifactId>
<version>2.1.1.RELEASEversion>
dependency>
<dependency>
<groupId>org.freemarkergroupId>
<artifactId>freemarkerartifactId>
<version>2.3.28version>
dependency>
模板文件:generationpdf.html,所在目录为src/main/resources/templates/generationpdf.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Titletitle>
<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>
GetHtmlContent.java:获取模板内容
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.*;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
public class GetHtmlContent {
/**
* 获取模板内容
* @param templateDirectory 模板文件夹
* @param templateName 模板文件名
* @param paramMap 模板参数
* @return
* @throws Exception
*/
public 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 = GetHtmlContent.class.getClassLoader();
URL resource = classLoader.getResource("templates");
String templateDirectory =resource.toURI().getPath();
String templateContent = GetHtmlContent.getTemplateContent(templateDirectory, "generationpdf.html", paramMap);
System.out.println(templateContent);
}
}
生成pdf文件,将date_time和date存储到HashMap中,然后将数据输出到pdf中
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
public class GeneratePDF {
/**
* HTML 转 PDF
* @param content html内容
* @param outPath 输出pdf路径
* @return 是否创建成功
*/
public static boolean html2Pdf(String content, String outPath) {
try {
Document document = new Document(); //创建一个标准的A4纸文档
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outPath));//书写器与ducument文档关联
document.open();//打开文档
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
new ByteArrayInputStream(content.getBytes()), null, Charset.forName("UTF-8"));
document.close();//关闭文档
} catch (Exception e) {
System.out.println("生成模板内容失败"+e.fillInStackTrace());
return false;
}
return true;
}
/**
* HTML 转 PDF
* @param content html内容
* @return PDF字节数组
*/
public static byte[] html2Pdf(String content) {
ByteArrayOutputStream outputStream = null;
try {
Document document = new Document();
outputStream = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
new ByteArrayInputStream(content.getBytes()), null, Charset.forName("UTF-8"));
document.close();
} catch (Exception e) {
System.out.println("------生成pdf失败-------");
}
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 = "src/main/resources/templates";
String templateContent = GetHtmlContent.getTemplateContent(templateDirectory, "generationpdf.html", paramMap);
GeneratePDF.html2Pdf(templateContent, outPath);
}
}
java实现生成PDF文件_xhga的博客-CSDN博客_java pdf
什么是 FreeMarker? - FreeMarker 中文官方参考手册 (foofun.cn)
iText官方教程_番薯(Koali)的博客-CSDN博客_itext官方文档
XMLWorkerHelper (root 5.5.9-SNAPSHOT API) (itextpdf.com)