package com.ltkj.web.config.pdfutils; import com.itextpdf.text.*; import com.itextpdf.text.pdf.*; import com.ltkj.common.utils.DateUtils; import java.io.IOException; import java.util.Date; /** * @Author: 西安路泰科技有限公司/lige * @Date: 2022/12/9 11:26 */ public class MyHeaderFooter extends PdfPageEventHelper { //总页数 PdfTemplate totalPage; //字体 Font hfFont; { try { hfFont = new Font(BaseFont.createFont("/Font/Deng.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED), 7); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } //打开文档时,创建一个总页数的模版 public void onOpenDocument(PdfWriter writer, Document document) { PdfContentByte cb = writer.getDirectContent(); totalPage = cb.createTemplate(50, 16); //共 页的宽高 } //一页加载完成触发,写入页眉和页脚 public void onEndPage(PdfWriter writer, Document document) { //创建一个两列的表格 PdfPTable table = new PdfPTable(2); try { table.setTotalWidth(PageSize.A4.getWidth()); //总宽度为A4纸张宽度 table.setLockedWidth(true); //锁定列宽 table.setWidths(new int[]{50, 50}); //设置每列宽度 PdfPCell cell = new PdfPCell(new Phrase("第" + document.getPageNumber() + "页/", hfFont)); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); //设置水平右对齐 cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //设置垂直居中 cell.disableBorderSide(15);//隐藏全部边框 table.addCell(cell); PdfPCell cell1 = new PdfPCell(Image.getInstance(totalPage)); //共 页 cell1.setHorizontalAlignment(Element.ALIGN_LEFT); //设置水平左对齐 cell1.setVerticalAlignment(Element.ALIGN_MIDDLE); //设置垂直居中 cell1.disableBorderSide(15);//隐藏全部边框 table.addCell(cell1); table.writeSelectedRows(0, -1, 0, 50, writer.getDirectContent()); } catch (Exception e) { throw new ExceptionConverter(e); } //生成左侧页眉 ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Paragraph("健康体检报告"+DateUtils.getDate(), hfFont), document.left(), PageSize.A4.getHeight() - 30, 0); // //生成右侧页眉 // ColumnText.showTextAligned(writer.getDirectContent(), // Element.ALIGN_RIGHT, new Paragraph(DateUtils.getDate(), hfFont), // document.right(), PageSize.A4.getHeight() - 30, 0); } // 全部完成后,将总页数的pdf模版写到指定位置 // public void onCloseDocument(PdfWriter writer, Document document) { // String text = "共" + (writer.getPageNumber()) + "页"; // ColumnText.showTextAligned(totalPage, Element.ALIGN_MIDDLE, new Paragraph(text, hfFont), 0, 0, 0); // } }