前言
继上次生成 PDF 后(详见使用 itext 将 html 页面转 pdf(完美支持中文),需求方追加生成页眉和页脚的需求.具体实现过程看代码!
核心代码
Document document = new Document(PageSize.A4);
PdfWriter pdfWriter = PdfWriter.getInstance(document, os);
pdfWriter.setPageEvent(new PdfHeaderFooter());
...
class PdfHeaderFooter extends PdfPageEventHelper {
Font bfChinese;
int fontSize = 10;
Image image;
@Override
public void onOpenDocument(PdfWriter writer, Document document) {
try {
bfChinese = new Font(BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), fontSize, Font.NORMAL, BaseColor.GRAY);
image = Image.getInstance(PDFUtil.class.getResource("/template/small.png"));
image.scalePercent(50);
image.setAbsolutePosition(8, document.top());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void onEndPage(PdfWriter writer, Document document) {
try {
Rectangle rect = new Rectangle(0, 38, 50, 50);
String line1 = String.format("- %d -", writer.getPageNumber());
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
new Phrase(line1, bfChinese),
(document.rightMargin() + document.right() + document.leftMargin() - document.left() - bfChinese.getBaseFont().getWidthPoint(line1, fontSize) / 2) / 2.0F,
document.bottom() - 22,
0);
String line2 = "本文件保密,未经允许,不得向任何第三方提供。";
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
new Phrase(line2, bfChinese),
(document.rightMargin() + document.right() + document.leftMargin() - document.left()) / 2.0F,
document.bottom() - 32,
0);
writer.getDirectContent().addImage(image);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于