wisdomisite-java/src/main/java/com/zhgd/xmgl/pdf/MyHeaderFooter3.java
2024-04-14 21:05:01 +08:00

63 lines
2.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.zhgd.xmgl.pdf;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
@Slf4j
public class MyHeaderFooter3 extends PdfPageEventHelper {
// 总页数
PdfTemplate totalPage;
Font hfFont;
{
try {
hfFont = new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 8, Font.NORMAL);
} catch (DocumentException e) {
log.error("error", e);
} catch (IOException e) {
log.error("error", e);
}
}
// 打开文档时,创建一个总页数的模版
public void onOpenDocument(PdfWriter writer, Document document) {
PdfContentByte cb =writer.getDirectContent();
totalPage = cb.createTemplate(30, 16);
}
// 一页加载完成触发,写入页眉和页脚
public void onEndPage(PdfWriter writer, Document document) {
PdfPTable table = new PdfPTable(3);
try {
table.setTotalWidth(PageSize.A3.getHeight() - 100);
table.setWidths(new int[] { 24, 24, 3});
table.setLockedWidth(true);
table.getDefaultCell().setFixedHeight(-10);
table.getDefaultCell().setBorder(Rectangle.BOTTOM);
table.addCell(new Paragraph("页脚", hfFont));// 可以直接使用addCell(str),不过不能指定字体,中文无法显示
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(new Paragraph("" + writer.getPageNumber() + "页/", hfFont));
// 总页数
PdfPCell cell = new PdfPCell(Image.getInstance(totalPage));
cell.setBorder(Rectangle.BOTTOM);
table.addCell(cell);
// 将页眉写到document中位置可以指定指定到下面就是页脚
// table.writeSelectedRows(0, -1, 50,PageSize.A4.getHeight() - 20, writer.getDirectContent());
table.writeSelectedRows(0, -1, 50,PageSize.A3.getHeight() - 1150, writer.getDirectContent());
} catch (Exception de) {
throw new ExceptionConverter(de);
}
}
// 全部完成后将总页数的pdf模版写到指定位置
public void onCloseDocument(PdfWriter writer,Document document) {
String text = "" + (writer.getPageNumber()) + "";
ColumnText.showTextAligned(totalPage, Element.ALIGN_LEFT, new Paragraph(text,hfFont), 2, 2, 0);
}
}