itextsharp添加页眉和页脚,显示页面边距不在页面边距之外。

时间:2013-07-19 06:23:38

标签: c# itextsharp

我是ItextSharp的新手,只是想知道如何在页面结束事件结束后将页眉和页脚放在边距之外?似乎当我使用onendpage事件而不是在页边距之外添加页脚时,它会添加页边距内部,并且当它应该超出底部边距时它总是会产生stackoverflow异常,它应该在边距之外添加?< / p>

是否有任何设置要在文档页脚中添加文本页边距(或填充)?

提前感谢。

2 个答案:

答案 0 :(得分:0)

发现它,我只是使用columntext,虽然我真的不想使用columntext :)并使用setsimplecolumn。

答案 1 :(得分:0)

由于您是iText的新手...当您在寻找有关某些特定主题的示例时,您应该首先查看来自Keyword listiText in Action — 2nd Edition样本。在您的情况下,关键字Header / footer是合适的。引用的第一个示例part1.chapter05.MovieHistory2已经向您展示了如何添加页眉和页脚。

首先,正如您自己已经提到的那样,您应该使用页面事件,onEndPage是准确的,最容易通过扩展PdfPageEventHelper.

来完成

此外,根据您似乎没有注意到的问题,您应该通过调用document.add或类似内容来添加页眉或页脚,因为此类添加会进入主页已经完成的区域(毕竟我们在onEndPage ...)。相反,您应该使用直接内容访问来定位页眉和页脚。

样本是这样的:

    /**
     * Adds the header and the footer.
     * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(
     *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
     */
    public void onEndPage(PdfWriter writer, Document document) {
        Rectangle rect = writer.getBoxSize("art");
        switch(writer.getPageNumber() % 2) {
        case 0:
            ColumnText.showTextAligned(writer.getDirectContent(),
                    Element.ALIGN_RIGHT, header[0],
                    rect.getRight(), rect.getTop(), 0);
            break;
        case 1:
            ColumnText.showTextAligned(writer.getDirectContent(),
                    Element.ALIGN_LEFT, header[1],
                    rect.getLeft(), rect.getTop(), 0);
            break;
        }
        ColumnText.showTextAligned(writer.getDirectContent(),
                Element.ALIGN_CENTER, new Phrase(String.format("page %d", pagenumber)),
                (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0);
    }

ColumnText.showTextAligned允许您将页眉,页脚等准确定位在页面上,通常位于顶部和底部边距之外的位置,而不会导致生成任何新页面或任何其他不需要的效果。< / p>

相关问题