最近项目里有个功能是要把前端展示的内容给导出pdf。经过一段时间的调研和尝试,最终选择了itext7来实现。网上有很多关于itext5的博客或者文档,但是关于itext7还挺少的。
首先介绍一下大体流程吧,项目是基于springboot 和vue 的前后端分离架构,基本思路是由前端生成html文件,传给后端,后端通过itext7转为pdf返回前端。废话少说,直接上代码!
由于不是我写的代码,这里只能给出参考:https://segmentfault.com/a/1190000015820792,我们的前端是基于这个方案改造的,很有参考价值。
com.itextpdf
html2pdf
3.0.2
com.itextpdf
font-asian
7.1.13
注意两个依赖的版本对应,进入html2pdf的pom文件就能看到itext的版本,font-asian的版本最低也要是html2pdf中itext7的版本。
导出pdf一般是需要水印和页码的,我们只要实现com.itextpdf.kernel.events.IEventHandler接口就可以了
水印
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();
}
}
页码
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.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后缀的字体需要添加,0
* @param outputStream 输出流
* @date : 2021/1/15 14:07
*/
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));
//添加中文字体支持
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 (StrUtil.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();
}
}
service
@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, "C:\\Windows\\Fonts\\微软雅黑\\msyh.ttc,0", outputStream);
}
}
controller,工具类用的是hutool的。
@Slf4j
@RestController
public class ExportPdfController {
@Autowired
private ExportPdfService exportPdfService;
@PostMapping("/export")
public void exportVehicleArchives(MultipartFile file, HttpServletResponse response) throws Exception {
try{
String fileNamePrefix = "文件名称";
String date = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN);
String fileName = fileNamePrefix + "_" + date +".pdf";
this.resolveResponse(response, fileName);
this.exportPdfService.exportPdf(file, response.getOutputStream());
} catch (Exception e) {
this.resetResponse(response, e);
}
}
private void resolveResponse(HttpServletResponse response, String fileName){
response.setContentType("application/pdf");
response.setCharacterEncoding("utf-8");
String encodeFileName = URLEncoder.createDefault().encode(fileName, StandardCharsets.UTF_8);
response.setHeader("Content-disposition", "attachment;filename=" + encodeFileName);
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
}
private void resetResponse(HttpServletResponse response, Exception exception)throws IOException {
// 重置response
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
String stacktrace = ExceptionUtil.stacktraceToString(exception);
log.error("{}", stacktrace);
String result = "下载文件失败," + exception.getMessage();
response.getWriter().println(result);
}
}
这样前端就能顺利导出pdf了
使用过程中难免会出现一些问题,百度直接找不到类似的问题,谷歌找到的很少,几乎没有参考价值。在此记录一些我遇到的问题
1、空指针异常
之前用的时候一直没啥问题,但是前端突然跟我说接口报错了。我就debug,搞了半天没发现问题在哪里。但是之前的html文件是没问题的,是不是后来的html文件和之前的哪里不一样导致的?我就比较两个文件有什么区别,前端说是不是 导致的?我把新的html文件删除 后,没有问题了,问题就这么解决了。
2、生成图片问题
看评论里有人问图片的问题,这个其实很简单,把图片转成base64放进html的img标签里就可以了。网络地址的图片我没试过,应该是不太行。
itext7明显比itext5好用很多,如果导出的pdf样式有问题,让前端修改一下html的样式就可以了,比如去除padding-left,去除label的对齐,图片小一点等等。我们前端一点一点的修改才最终导出了符合产品的pdf。