1. 项目目录
2. pom.xml
<!-- html 转 pdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>3.0.2</version>
</dependency>
<!-- 中文字体支持 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>font-asian</artifactId>
<version>7.1.13</version>
</dependency>
<!-- 流处理 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<!-- 读取 resource 目录下文件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.6.3</version>
</dependency>
3. 创建 Service
TestService
package com.cnbai.service;
import com.cnbai.utils.HtmlToPdfUtils;
import org.springframework.core.io.ClassPathResource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 根据 html 文件生成 pdf 文件
*/
public class TestService {
/** html 文件路径 */
private static final String HTML_PATH = "html/test.html";
/** 项目所在路径 */
private static final String PATH = System.getProperty("user.dir");
/**
* 测试
*/
public static void main(String[] args) {
try {
String path = generatePdf(HTML_PATH);
System.out.println("文件路径:" + path);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 生成 pdf 文件
*/
private static String generatePdf(String path) throws Exception {
String pdfDirPath = PATH + File.separator + "pdf" + File.separator;
File file = new File(pdfDirPath);
if (!file.exists()) {
file.mkdirs();
}
String pdfPath = pdfDirPath + "测试.pdf";
ClassPathResource classPathResource = new ClassPathResource(path);
InputStream inputStream = classPathResource.getInputStream();
OutputStream outputStream = new FileOutputStream(pdfPath);
HtmlToPdfUtils.convertToPdf(inputStream, outputStream);
return pdfPath;
}
}
4. 创建工具类
HtmlToPdfUtils
package com.cnbai.utils;
import com.cnbai.pdf.HeaderMarkerEventHandler;
import com.cnbai.pdf.PageEventHandler;
import com.cnbai.pdf.WaterMarkEventHandler;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.io.source.ByteArrayOutputStream;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.font.FontProvider;
import org.springframework.core.io.ClassPathResource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 使用 itext7 将 html 生成 pdf
*/
public class HtmlToPdfUtils {
/**
* 自定义水印
*/
private static final String WATERMARK_TEXT = "cnbai";
/**
* 页眉显示
*/
private static final String headerText = "hahaha";
/**
* 页眉logo
*/
private static final String logoUrl = "http://localhost/logo.jpg";
/**
* 自定义字体路径,ttc后缀的字体需要添加 -> ,0
*/
private static final String FONT_PATH = "/font/simsun.ttc";
/**
* html 转 pdf
*
* @param inputStream 输入流
* @param outputStream 输出流
*/
public static void convertToPdf(InputStream inputStream, OutputStream outputStream) throws IOException {
PdfWriter pdfWriter = new PdfWriter(outputStream);
PdfDocument pdfDocument = new PdfDocument(pdfWriter);
// 设置为 A4 大小
pdfDocument.setDefaultPageSize(PageSize.A4);
// 添加中文字体支持
ConverterProperties properties = new ConverterProperties();
FontProvider fontProvider = new FontProvider();
// 添加自定义字体, 例如宋体
ClassPathResource classPathResource = new ClassPathResource(FONT_PATH);
String fontPath = classPathResource.getPath() + ",0";
PdfFont microsoft = PdfFontFactory.createFont(fontPath, PdfEncodings.IDENTITY_H, false);
fontProvider.addFont(microsoft.getFontProgram(), PdfEncodings.IDENTITY_H);
// 添加页眉
pdfDocument.addEventHandler(PdfDocumentEvent.START_PAGE, new HeaderMarkerEventHandler(microsoft, headerText, logoUrl));
// 添加水印
pdfDocument.addEventHandler(PdfDocumentEvent.INSERT_PAGE, new WaterMarkEventHandler(WATERMARK_TEXT));
// 添加页码
pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE, new PageEventHandler(microsoft));
properties.setFontProvider(fontProvider);
// 读取 Html 文件流,查找出当中的 或出现类似的符号空格字符
inputStream = readInputStream(inputStream);
if (inputStream != null) {
// 生成 pdf 文档
HtmlConverter.convertToPdf(inputStream, pdfDocument, properties);
pdfWriter.close();
pdfDocument.close();
} else {
System.out.println("转换失败!");
}
}
/**
* 读取 HTML 流文件,并查询当中的 或类似符号,并将其替换为空格
*/
private static InputStream readInputStream(InputStream inputStream) {
try {
// 1. 创建字节数组输出流,用来输出读取到的内容
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 2. 创建缓存大小,1KB
byte[] buffer = new byte[1024];
int len; // 每次读取到内容的长度
// 3. 开始读取输入流中的内容
while ((len = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
// 4. 把字节数组转换为字符串
String content = baos.toString();
// 5. 关闭输入流和输出流
inputStream.close();
baos.close();
// 6. 判断 HTML 内容是否具有 HTML 的特殊字符标记
Pattern compile = Pattern.compile("&[a-zA-Z]{1,10};", Pattern.CASE_INSENSITIVE);
Matcher matcher = compile.matcher(content);
String replaceAll = matcher.replaceAll("");
// 7. 将字符串转化为输入流返回
return getStringStream(replaceAll);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将一个字符串转化为输入流
*/
private static InputStream getStringStream(String sInputString) {
if (sInputString != null && !sInputString.trim().isEmpty()) {
try {
return new ByteArrayInputStream(sInputString.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
}
5. 创建配置类
HeaderMarkerEventHandler
package com.cnbai.pdf;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;
import org.springframework.util.StringUtils;
import java.net.MalformedURLException;
import java.net.URL;
/**
* 生成 pdf 页眉
*/
public class HeaderMarkerEventHandler implements IEventHandler {
/**
* pdf字体
*/
private final PdfFont pdfFont;
/**
* 页眉显示
*/
private final String title;
/**
* logo地址
*/
private String logoUrl;
public HeaderMarkerEventHandler(PdfFont pdfFont, String title) {
this.pdfFont = pdfFont;
this.title = title;
}
public HeaderMarkerEventHandler(PdfFont pdfFont, String title, String logoUrl) {
this.pdfFont = pdfFont;
this.title = title;
this.logoUrl = logoUrl;
}
@Override
public void handleEvent(Event event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
PdfDocument pdf = docEvent.getDocument();
PdfPage page = docEvent.getPage();
Rectangle pageSize = page.getPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(page.getLastContentStream(), page.getResources(), pdf);
Canvas canvas = new Canvas(pdfCanvas, pageSize);
float x = pageSize.getRight() - 60;
float y = pageSize.getTop() - 32;
Paragraph p = new Paragraph(title)
.setFontSize(9)
.setFont(pdfFont);
// 显示在顶部右侧位置
canvas.showTextAligned(p, x, y, TextAlignment.RIGHT);
if (!StringUtils.isEmpty(logoUrl)) {
try {
URL url = new URL(logoUrl);
Image logo = new Image(ImageDataFactory.create(url));
logo.scaleAbsolute(100, 20);
logo.setMarginLeft(30);
logo.setMarginTop(15);
canvas.add(logo);
} catch (MalformedURLException e) {
System.out.println("logo 无法解析: " + logoUrl);
}
}
canvas.close();
}
}
PageEventHandler
package com.cnbai.pdf;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;
/**
* 生成 pdf 页码
*/
public class PageEventHandler implements IEventHandler {
/**
* pdf字体
*/
private final PdfFont pdfFont;
public PageEventHandler(PdfFont pdfFont) {
this.pdfFont = pdfFont;
}
@Override
public void handleEvent(Event event) {
PdfDocumentEvent documentEvent = (PdfDocumentEvent) event;
PdfDocument document = documentEvent.getDocument();
PdfPage page = documentEvent.getPage();
Rectangle pageSize = page.getPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(page.getLastContentStream(), page.getResources(), document);
Canvas canvas = new Canvas(pdfCanvas, pageSize);
float x = (pageSize.getLeft() + pageSize.getRight()) / 2;
float y = pageSize.getBottom() + 15;
Paragraph paragraph =
new Paragraph("第" + document.getPageNumber(page) + "页/共" + document.getNumberOfPages() + "页")
.setFontSize(10)
.setFont(pdfFont);
canvas.showTextAligned(paragraph, x, y, TextAlignment.CENTER);
canvas.close();
}
}
WaterMarkEventHandler
package com.cnbai.pdf;
import com.itextpdf.kernel.colors.WebColors;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.VerticalAlignment;
import java.io.IOException;
/**
* 生成 pdf 水印
*/
public class WaterMarkEventHandler implements IEventHandler {
/**
* 水印内容
*/
private final String waterMarkContent;
/**
* 一页中有几列水印
*/
private final int waterMarkX;
/**
* 一页中每列有多少水印
*/
private final int waterMarkY;
public WaterMarkEventHandler(String waterMarkContent) {
this(waterMarkContent, 5, 5);
}
public WaterMarkEventHandler(String waterMarkContent, int waterMarkX, int waterMarkY) {
this.waterMarkContent = waterMarkContent;
this.waterMarkX = waterMarkX;
this.waterMarkY = waterMarkY;
}
@Override
public void handleEvent(Event event) {
PdfDocumentEvent documentEvent = (PdfDocumentEvent) event;
PdfDocument document = documentEvent.getDocument();
PdfPage page = documentEvent.getPage();
Rectangle pageSize = page.getPageSize();
PdfFont pdfFont = null;
try {
pdfFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
} catch (IOException e) {
e.printStackTrace();
}
PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamAfter(), page.getResources(), document);
Paragraph waterMark = new Paragraph(waterMarkContent).setOpacity(0.5f);
Canvas canvas = new Canvas(pdfCanvas, pageSize)
.setFontColor(WebColors.getRGBColor("lightgray"))
.setFontSize(16)
.setFont(pdfFont);
for (int i = 0; i < waterMarkX; i++) {
for (int j = 0; j < waterMarkY; j++) {
canvas.showTextAligned(waterMark, (150 + i * 300), (160 + j * 150), document.getNumberOfPages(),
TextAlignment.CENTER, VerticalAlignment.BOTTOM, 120);
}
}
canvas.close();
}
}
6. 创建 Html 文件
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试标题</title>
</head>
<body>
cnbai
<img src="http://localhost/image.jpg">
<img src="upload/test.jpg">
</body>
</html>
7. 字体文件
字体文件在本地 windows 拷贝出来,放在图中目录下