如何将文本添加为 页眉或页脚?

问题描述 投票:1回答:2

我正在用iText 5创建一个pdf并希望添加一个页脚。我做了第14章中的“iText in action”一书。

没有错误,但页脚没有出现。谁能告诉我我做错了什么?

我的代码:

public class PdfBuilder {

    private Document document;

    public void newDocument(String file) {
        document = new Document(PageSize.A4);
        writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        MyFooter footerEvent = new MyFooter();
        writer.setPageEvent(footerEvent);
        document.open();

        ...

        document.close();
        writer.flush();
        writer.close();
    }

    class MyFooter extends PdfPageEventHelper {

    public void onEndPage(PdfWriter writer, Document document) {
        PdfContentByte cb = writer.getDirectContent();
        ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer(), (document.right() - document.left()) / 2
                + document.leftMargin(), document.top() + 10, 0);

    }

    private Phrase footer() {
        Font ffont = new Font(Font.FontFamily.UNDEFINED, 5, Font.ITALIC);
        Phrase p = new Phrase("this is a footer");
        return p;
    }
}
java pdf-generation itext
2个回答
1
投票

您报告的问题无法复制。我已经举了你的例子,我用这个事件创建了TextFooter示例:

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);
    }
}

请注意,我通过仅创建一次FontParagraph实例来提高性能。我还介绍了一个页脚和标题。您声称要添加页脚,但实际上您添加了标题。

top()方法为您提供了页面的顶部,所以也许您打算计算相对于页面的ybottom()位置。

您的footer()方法也有错误:

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

你定义了一个名为Fontffont,但你没有使用它。我想你打算写:

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

现在,当我们查看resulting PDF时,我们清楚地看到作为页眉和页脚添加到每个页面的文本。


0
投票

通过使用PdfContentByte的showTextAligned方法我们可以在页面中添加页脚。我们不应该将短语内容作为字符串传递给showTextAligned方法作为参数之一。如果要在将其传递给方法之前格式化页脚内容。下面是示例代码。

 PdfContentByte cb = writer.getDirectContent();
 cb.showTextAligned(Element.ALIGN_CENTER, "this is a footer", (document.right() - document.left()) / 2 + document.leftMargin(), document.bottom() - 10, 0);
© www.soinside.com 2019 - 2024. All rights reserved.