Java 使用 itextpdf 生成(导出)PDF时,添加自定义页脚,当前案例演示 页码居中,单据编号右侧显示,实现代码如下:
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import java.io.FileOutputStream;
import java.io.IOException;
public class SimplePdfFooterWithTotalPages {
public static void main(String[] args) {
String outputPath = "C:\\Users\\***\\Desktop\\导出模板_success_table.pdf"; //生成的PDF保存路径
try {
// 创建文档对象
Document document = new Document();
// 创建PDF写入器
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputPath));
document.open();
// 创建模板用于总页数
final PdfTemplate totalPageTemplate = writer.getDirectContent().createTemplate(30, 16);
// 设置单据编号
String documentNumber = "DOC-2023-001";
// 添加页脚事件处理
//设置字体,支持中文
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font footerFont = new Font(bf, 10);
writer.setPageEvent(new PdfPageEventHelper() {
// 在每页结束时添加页脚
public void onEndPage(PdfWriter writer, Document document) {
try {
PdfContentByte cb = writer.getDirectContent();
//计算页脚居中位置
float center = (document.left() + document.right()) / 2;
float bottom = document.bottom() - 20;
//构建页脚中页码文本("第 X 页 / 共"部分)
String pageText = "第 " + writer.getPageNumber() + " 页 / 共";
//添加居中页码(第一部分)
ColumnText.showTextAligned(
cb,
Element.ALIGN_CENTER,
new Phrase(pageText, footerFont),
center,
bottom,
0
);
//添加总页数模板(将在文档关闭时填充)
//计算模板开始位置(显示"第 X 页 / 共"部分 之后的总页数部分 X 页)
float totalNumberX = center + (footerFont.getBaseFont().getWidthPoint(pageText + "00", 10) / 2);
cb.addTemplate(
totalPageTemplate,
totalNumberX ,
bottom
);
//添加总页数后的"页"字
ColumnText.showTextAligned(
cb,
Element.ALIGN_LEFT,
new Phrase(" 页", footerFont),
totalNumberX + footerFont.getBaseFont().getWidthPoint("00", 10),
bottom,
0
);
//添加右侧单据编号
ColumnText.showTextAligned(
cb,
Element.ALIGN_RIGHT,
new Phrase("单据编号: " + documentNumber, footerFont),
document.right() - 36,
bottom,
0
);
} catch (Exception e) {
e.printStackTrace();
}
}
// 文档关闭时填充总页数
public void onCloseDocument(PdfWriter writer, Document document) {
// 使用中文字体填充总页数
try {
ColumnText.showTextAligned(
totalPageTemplate,
Element.ALIGN_LEFT,
new Phrase(String.valueOf(writer.getPageNumber()), footerFont),
0,
0,
0
);
} catch (Exception e) {
e.printStackTrace();
}
}
});
// 添加一些内容(演示用)
for (int i = 0; i < 500; i++) {
document.add(new Paragraph("这是文档的第 " + (i+1) + " 段内容。"));
document.add(Chunk.NEWLINE);
}
// 关闭文档
document.close();
System.out.println("PDF with footer created successfully!");
} catch (DocumentException | IOException e) {
e.printStackTrace();
}
}
}
页脚显示字体样式及位置可以根据实际情况进行调整。
导出页脚示例: