使用Itext为PDF添加页眉(图像)和页脚(文字)

  |   0 评论   |   565 浏览

前言

继上次生成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);
        }
    }


}

评论

发表评论

validate