How to add text as a header or footer?

给你一囗甜甜゛ 提交于 2019-11-29 13:03:15

The problem you report can not be reproduced. I have taken your example and I create the TextFooter example with this event:

class MyFooter extends PdfPageEventHelper {
    Font ffont = new Font(Font.FontFamily.UNDEFINED, 5, Font.ITALIC);

    public void onEndPage(PdfWriter writer, Document document) {
        PdfContentByte cb = writer.getDirectContent();
        Phrase header = new Phrase("this is a header", ffont);
        Phrase footer = new Phrase("this is a footer", ffont);
        ColumnText.showTextAligned(cb, Element.ALIGN_CENTER,
                header,
                (document.right() - document.left()) / 2 + document.leftMargin(),
                document.top() + 10, 0);
        ColumnText.showTextAligned(cb, Element.ALIGN_CENTER,
                footer,
                (document.right() - document.left()) / 2 + document.leftMargin(),
                document.bottom() - 10, 0);
    }
}

Note that I improved the performance by creating the Font and Paragraph instance only once. I also introduced a footer and a header. You claimed you wanted to add a footer, but in reality you added a header.

The top() method gives you the top of the page, so maybe you meant to calculate the y position relative to the bottom() of the page.

There was also an error in your footer() method:

private Phrase footer() {
    Font ffont = new Font(Font.FontFamily.UNDEFINED, 5, Font.ITALIC);
    Phrase p = new Phrase("this is a footer");
    return p;
}

You define a Font named ffont, but you don't use it. I think you meant to write:

private Phrase footer() {
    Font ffont = new Font(Font.FontFamily.UNDEFINED, 5, Font.ITALIC);
    Phrase p = new Phrase("this is a footer", ffont);
    return p;
}

Now when we look at the resulting PDF, we clearly see the text that was added as a header and a footer to each page.

By using showTextAligned method of PdfContentByte We can add footer to our page. Instead of phrase we should pass footer content as string to showTextAligned method as one of the parameter. If you want to format your footer content do before passing it to the method. Below is the sample code.

 PdfContentByte cb = writer.getDirectContent();
 cb.showTextAligned(Element.ALIGN_CENTER, "this is a footer", (document.right() - document.left()) / 2 + document.leftMargin(), document.bottom() - 10, 0);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!