爲了實現頁眉和頁腳您需要實現擴展
PdfPageEventHelper類的iText API的類的HeaderFooter。然後覆蓋onEndPage()
設置頁眉和頁腳。在這個例子中,我在頁眉中設置了name
,在頁腳中設置了「頁面數量」。
在創建PDF端代碼,你需要使用HeaderAndFooter
類是這樣的:
Document document = new Document(PageSize.LETTER);
PdfWriter writer = PdfWriter.getInstance(document, "C:\sample.pdf");
//set page event to PdfWriter instance that you use to prepare pdf
writer.setPageEvent(new HeaderAndFooter(name));
.... //Add your content to documne here and close the document at last
/*
* HeaderAndFooter class
*/
public class HeaderAndFooter extends PdfPageEventHelper {
private String name = "";
protected Phrase footer;
protected Phrase header;
/*
* Font for header and footer part.
*/
private static Font headerFont = new Font(Font.COURIER, 9,
Font.NORMAL,Color.blue);
private static Font footerFont = new Font(Font.TIMES_ROMAN, 9,
Font.BOLD,Color.blue);
/*
* constructor
*/
public HeaderAndFooter(String name) {
super();
this.name = name;
header = new Phrase("***** Header *****");
footer = new Phrase("**** Footer ****");
}
@Override
public void onEndPage(PdfWriter writer, Document document) {
PdfContentByte cb = writer.getDirectContent();
//header content
String headerContent = "Name: " +name;
//header content
String footerContent = headerContent;
/*
* Header
*/
ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase(headerContent,headerFont),
document.leftMargin() - 1, document.top() + 30, 0);
/*
* Foooter
*/
ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, new Phrase(String.format(" %d ",
writer.getPageNumber()),footerFont),
document.right() - 2 , document.bottom() - 20, 0);
}
}
希望它能幫助。我已經在一個通用中使用了它。
感謝您的回答。虐待您的代碼馬上。 – Weddy 2013-04-10 07:57:03
我想出了另一種方式,但這很有幫助。希望這可以幫助其他用戶:D – Weddy 2013-04-10 09:16:48
感謝您的回答。我只需要一個添加如下:在頁腳中,我有3行,每個字體大小不同。如何在頁腳中添加這三行不同的字體。我如何估計字體高度,並根據設置其垂直值 - document.bottom() - XXXX? – dsi 2013-09-17 12:09:15