繁体   English   中英

使用ITEXT以PDF格式显示页码

[英]Show page numbers in PDF using ITEXT

我们使用Itext在我们的Web应用程序中生成PDF。 PDF正在正确生成。

我需要在页脚中显示一些版权信息以及页码。 我需要在底部的左侧显示版权信息,而在底部的右侧显示页码。

我已经浏览了谷歌和一些文章,使用它们我可以在底部添加页脚。 但是这个页脚仅显示底部右侧的版权。

如何使用Itext为此添加页码?

以下是我用于在页脚右侧生成版权信息的代码。

    static class HeaderFooter extends PdfPageEventHelper {
    public void onEndPage(PdfWriter writer, Document document) {
        Rectangle rect = writer.getBoxSize("footer");
        BaseFont bf_times;
        try {
            bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252",
                    false);
            Font font = new Font(bf_times, 9);
            ColumnText.showTextAligned(writer.getDirectContent(),
                    Element.ALIGN_LEFT, new Phrase("Copyright 2011",
                            font), (rect.getLeft() + rect.getRight()) / 2,
                    rect.getBottom() - 18, 0);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

以下是用于显示页码的代码。 我无法将这两者结合起来同时显示页码和版权信息。

ColumnText.showTextAligned(writer.getDirectContent(),
    Element.ALIGN_RIGHT,
    new Phrase(String.format("%d", writer.getPageNumber()),
            font), (rect.getLeft() + rect.getRight()) / 2,
    rect.getBottom() - 18, 0);

showTextAligned函数采用以下参数。

public static void showTextAligned(PdfContentByte canvas,
                                   int alignment,
                                   Phrase phrase,
                                   float x,
                                   float y,
                                   float rotation)

在您的示例中,您将两个项目的x值设置为相同的值,因此您可能正在将一个文本写入另一个文本。 尝试调整x值以查看是否有帮助。

具体来说,尝试设置代码的页码块,使其与页脚矩形的右侧对齐。

ColumnText.showTextAligned(writer.getDirectContent(),
    Element.ALIGN_RIGHT,
    new Phrase(String.format("%d", writer.getPageNumber()),
            font),  rect.getRight(),
    rect.getBottom() - 18, 0);

此外,您可以使用PDFStamper将事实后的页眉和页脚添加到PDF文档。 有时这可能是一种更简单的方法。 iText in Action书中有几个例子。 这是其中一个的代码示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM