2013-07-19 200 views
0

我是ItextSharp的新手,只是想知道如何在页面事件结束后在页边空白处放置页眉和页脚?似乎当我使用onendpage事件而不是在页边距之外添加页脚时,它会在页边距内部添加页脚,并且它总是会在底部边距上产生stackoverflow异常,并且它应该添加到页边距之外?itextsharp添加页眉和页脚,显示在页边距内页边距之外。

是否有任何设置可告诉在文档页脚中添加边距(或填充)之外的文本?

在此先感谢。

回答

0

由于您是iText的新手......当您在寻找关于某个特定主题的样本时,您应该先查看Keyword list以获取iText 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允许你定位页眉,页脚等正是你希望他们在页面上,顶部和底部边缘外的正常,没有造成任何新要生成的页面或任何其他不需要的效果。

0

发现它,我只是使用columntext,但我真的很喜欢不使用columntext :)并使用setsimplecolumn。