John
John

Reputation: 750

Add header to only the first PDF page using Itext in java

I am using iText for generating PDF documents in my project and it is working fine. I am adding header and footer in the onEndPage method with writer.setPageEvent.

@Override
    public void onEndPage(PdfWriter writer, Document document) {
        try {
            addHeader(writer);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        addFooter(writer);
    }

My problem is I want to display the header only on the first page and not in subsequent pages. But the header is getting displayed on all the pages.

Upvotes: 0

Views: 2148

Answers (2)

mkl
mkl

Reputation: 95918

If you want to add a header only on a single page, in particular the first document page, you don't need to use page events at all! Page events are good for adding similar stuff on many pages or even adding stuff on only few pages which you determine via events but for the case at hand, adding a header to the first page only, they are not needed at all.

Thus, as an alternative to the flag in the event listener as proposed by @Soufiane Sakhi in his answer, you could completely remove the addHeader(writer) call from the onEndPage method:

public void onEndPage(PdfWriter writer, Document document) {
    addFooter(writer);
}

and execute it right after opening your document (when the first page is the current page)

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
writer.setPageEvent(YOUR_PAGE_EVENT_LISTENER);
document.open();
addHeader(writer);

Upvotes: 1

user6365858
user6365858

Reputation:

You can add a field to the PdfPageEventHelper to check if it's the first page, something like this:

private boolean firstPage = true;

@Override
public void onEndPage(PdfWriter writer, Document document) {
    try {
        if (firstPage) {
            firstPage = false;
            addHeader(writer);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    addFooter(writer);
}

Upvotes: 0

Related Questions