前言
最近项目里有个功能是要把前端展示的内容给导出pdf。经过一段时间的调研和尝试,最终选择了itext7来实现。网上有很多关于itext5的博客或者文档,但是关于itext7还挺少的。
首先介绍一下大体流程吧,项目是基于springboot 和vue 的前后端分离架构,基本思路是由前端生成html文件,传给后端,后端通过itext7转为pdf返回前端。废话少说,直接上代码!
一、前端处理html
可参考:https://segmentfault.com/a/1190000015820792,也可使用postman测试的时候传入下面的html
<!DOCTYPE html>
<html>
<head>
<title>简单简历</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="cache-control" content="no-cache, no-store, must-revalidate"/>
<meta http-equiv="pragma" content="no-cache"/>
<meta http-equiv="expires" content="0"/>
<!-- 自定义样式 -->
<style>
*{
font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;
}
body {
margin: 0;
padding: 0;
}
a {
text-decoration: none;
padding: 0;
margin: 5px 0;
color: black;
}
a:hover {
color: #5c8dff;
}
b{
margin: 0 10px;
}
/* 主体 */
.main {
/*margin: 0 auto;*/
/*width: 770px;*/
/*box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);*/
/*border: 1px solid #dad8d8;*/
/*background: #fbfbfb;*/
}
/* 1级标题 */
h3.list1 {
color: #409EFF;
border-bottom: 1px solid #409EFF;
padding: 5px;
margin: 50px 0 0 0;
}
/* 大模块 */
.block,.block1 {
/*background: #efefef;*/
/*border: 1px solid #dad8d8;*/
margin: 0 0 20px 0;
padding: 0 10px;
}
.block,.block1 p {
text-indent:2em;
}
.block:hover {
background: #eeeeee;
}
.block1:hover {
background: #cecece;
}
.button-list{
text-align: center;
margin: 20px auto;
padding: 10px;
width: 1024px;
}
</style>
</head>
<body>
<!-- 简历主体 -->
<div id="body" class="main">
<div class="section">
<div class="module">
<h3 class="list1" style="margin: 0;">基本信息</h3>
<div class="block">
<p>XXX<b>/</b>男<b>/</b>25岁</p>
<p>本科<b>/</b>XX学校<b>/</b>XX专业<b>/</b>2014-2018</p>
<p>工龄:X年</p>
<p>手机:XXXXXXXXXX</p>
<p>邮箱:XXXXX@qq.com</p>
<p>GitHub:<a href="https://github.com/huanzi-qch">https://github.com/huanzi-qch</a></p>
<p>博客园:<a href="https://www.cnblogs.com/huanzi-qch">https://www.cnblogs.com/huanzi-qch</a></p>
<br/>
<p>求职岗位:Java开发<b>/</b>目标城市:南宁市<b>/</b>期望薪资:面议</p>
<p>注:已离职,一个月可到岗</p>
<img style="position: relative;top: -350px;left: 500px;width: 100px;height: 130px;" src="1@2x.png"/>
</div>
</div>
<div class="module">
<h3 class="list1">技能清单</h3>
<div class="block">
<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
<p>熟悉XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。</p>
</div>
</div>
<div class="module">
<h3 class="list1">工作经历</h3>
<div class="block">
<p>XXX技术有限公司<b>/</b>Java开发工程师<b>/</b>2018.01 - 至今</p>
<p>参与多个项目开发、测试、部署等工作,包括:</p>
<p>1、XXX。</p>
<p>2、XXX。</p>
<p>3、XXX。</p>
</div>
</div>
<div class="module">
<h3 class="list1">项目经历</h3>
<div class="block">
<h4 class="list2">项目1</h4>
<div class="block1">
<p>项目名称:XXX(2020-11 —2021-11)</p>
<p>项目介绍:XXXXXXXXXXXXXXX。</p>
<p>技术架构:XXX + XXX + XXX。</p>
<p>职责描述:</p>
<p>1、XXXX。</p>
<p>2、XXXX。</p>
<p>3、XXXX。</p>
<p>4、XXXX。</p>
</div>
<h4 class="list2">项目2</h4>
<div class="block1">
<p>项目名称:XXX(2020-11 —2021-11)</p>
<p>项目介绍:XXXXXXXXXXXXXXX。</p>
<p>技术架构:SpringBoot + Vue + Element-UI + ECharts。</p>
<p>职责描述:</p>
<p>1、XXXX。</p>
<p>2、XXXX。</p>
<p>3、XXXX。</p>
<p>4、XXXX。</p>
</div>
</div>
</div>
<div class="module">
<h3 class="list1">自我评价</h3>
<div class="block">
<p>1、XXXX;</p>
<p>2、XXXX;</p>
<p>3、XXXX;</p>
</div>
</div>
</div>
</div>
</body>
</html>
二、后端引入依赖
<!-- itext7html转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>
注意两个依赖的版本对应,进入html2pdf的pom文件就能看到itext的版本,font-asian的版本最低也要是html2pdf中itext7的版本。
三 、水印和页码
水印代码:
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;
/**
* 处理水印
*/
public class WaterMarkEventHandler implements IEventHandler {
/**
* 水印内容
*/
private String waterMarkContent;
/**
* 一页中有几列水印
*/
private int waterMarkX;
/**
* 一页中每列有多少水印
*/
private 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();
}
}
页码代码:
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 java.io.IOException;
/**
* 处理页码
*/
public class PageEventHandler implements IEventHandler {
@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.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();
}
}
四、添加转换工具类
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
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 java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class HtmlToPdfUtils {
/**
* html转pdf
* @param inputStream 输入流
* @param waterMark 水印
* @param fontPath 字体路径,ttc后缀的字体需要添加<b>,0<b/>
* @param outputStream 输出流
*/
public static void convertToPdf(InputStream inputStream, String waterMark, String fontPath, OutputStream outputStream) throws IOException {
PdfWriter pdfWriter = new PdfWriter(outputStream);
PdfDocument pdfDocument = new PdfDocument(pdfWriter);
//设置为A4大小
pdfDocument.setDefaultPageSize(PageSize.A4);
//添加水印
pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE, new WaterMarkEventHandler(waterMark));
//添加页码
//pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE,new PageEventHandler());
//添加中文字体支持
ConverterProperties properties = new ConverterProperties();
FontProvider fontProvider = new FontProvider();
PdfFont sysFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
fontProvider.addFont(sysFont.getFontProgram(), "UniGB-UCS2-H");
//添加自定义字体,例如微软雅黑
/*if (StringUtils.isNotBlank(fontPath)){
PdfFont microsoft = PdfFontFactory.createFont(fontPath, PdfEncodings.IDENTITY_H, false);
fontProvider.addFont(microsoft.getFontProgram(), PdfEncodings.IDENTITY_H);
}*/
properties.setFontProvider(fontProvider);
HtmlConverter.convertToPdf(inputStream, pdfDocument, properties);
pdfWriter.close();
pdfDocument.close();
}
}
五、Java 调用工具类
service
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.io.OutputStream;
@Service
public class ExportPdfService {
public void exportPdf(MultipartFile file, OutputStream outputStream) throws Exception {
String waterMarkText = "自定义水印";
InputStream inputStream = file.getInputStream();
//微软雅黑在windows系统里的位置如下,linux系统直接拷贝该文件放在linux目录下即可
HtmlToPdfUtils.convertToPdf(inputStream, waterMarkText, "", outputStream);
}
}
controller
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
/**
* 使用itext7html转pdf
*/
@Slf4j
@RestController
public class ExportPdfController {
@Resource
private ExportPdfService exportPdfService;
/**
* @param file html文件
* @param response
* @param request
* @throws Exception
*/
@PostMapping("/export")
public void exportVehicleArchives(MultipartFile file, HttpServletResponse response,HttpServletRequest request) throws Exception {
try{
String fileNamePrefix = "文件名称";
String date = format(new Date(), "yy-mm-dd HH:mm");
String fileName = fileNamePrefix + "_" + date +".pdf";
this.resolveResponse(request,response, fileName);
this.exportPdfService.exportPdf(file, response.getOutputStream());
} catch (Exception e) {
this.resetResponse(response, e);
}
}
private void resolveResponse(HttpServletRequest request,HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
response.setContentType("application/pdf");
response.setCharacterEncoding("utf-8");
setFileDownloadHeader(request,response,fileName);
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
}
/**
* 防止浏览器下载文件名中文乱码
* @param request
* @param response
* @param fileName
*/
public void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
String userAgent = request.getHeader("USER-AGENT");
try {
String finalFileName = null;
if(StringUtils.contains(userAgent, "MSIE")||StringUtils.contains(userAgent, "Trident") || StringUtils.contains(userAgent,"Edge")){//IE 浏览器
finalFileName = URLEncoder.encode(fileName,"UTF8");
}else{
finalFileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
}
response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");//\" 解决Firefox下载英文+中文组合的文件名的问题
} catch (UnsupportedEncodingException e) {
}
}
private void resetResponse(HttpServletResponse response, Exception exception)throws IOException {
// 重置response
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
String result = "下载文件失败," + exception.getMessage();
response.getWriter().println(result);
}
/**
* 格式化日期
* @param date
* @param pattern
* @return
*/
public String format(Date date,String pattern){
Instant instant = date.toInstant();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
}
}
注意
itext7明显比itext5好用很多,如果导出的pdf样式有问题,让前端修改一下html的样式就可以了,比如去除padding-left,去除label的对齐,图片小一点等等。我们前端一点一点的修改才最终导出了符合产品的pdf。
博主写的很好,转发收藏
参考文档:
java使用itext7实现html转pdf_红藕香残玉簟秋的博客-CSDN博客_html转pdf itext
下面一篇itext5 实践文档也不错:SpringBoot导出pdf文件学习_遨游在知识的海洋无法自拔的博客-CSDN博客_springboot导出pdf