Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

c# - itextsharp: How to generate a report with dynamic header in PDF using itextsharp?

I'm generating a PDF report with itextsharp, the header of the report has the information of the Customer, In the body of the report contains a list of customer transactions.

My doubt is: How to generate a header dynamically for each client?

I need an example to generate a header dynamically to the report. Every new page Header need to have the data that client when changing client header should contain information on the new client.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your question risks down-voting or at least comments in the sense of "What have you tried?"

However, I've written you a small example in Java which you can easily adapt to C# as iText and iTextSharp share more or less the same syntax.

The example is called VariableHeader and these are the most interesting snippets:

First I create a custom implementation of the PdfPageEvent interface (using PdfPageEventHelper). It's important to understand that you can't use the onStartPage() method (for reasons described in my book), use the onEndPage() method instead.

public class Header extends PdfPageEventHelper {

    protected Phrase header;

    public void setHeader(Phrase header) {
        this.header = header;
    }

    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        PdfContentByte canvas = writer.getDirectContentUnder();
        ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, header, 559, 806, 0);
    }
}

As you can see, the text of the header is stored in a variable that can be changed using the setHeader() method we created.

The event is declared to the PdfWriter like this:

PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
Header event = new Header();
writer.setPageEvent(event);

I change the header Phrase before invoking the newPage() method:

event.setHeader(new Phrase(String.format("THE FACTORS OF %s", i)));
document.newPage();

In my simple example, I generate a document that lists the factors of all the numbers from 2 to 300: variable_header.pdf. The header of each page says "THE FACTORS OF X" where X is the number of which the factors are shown on that page.

You can easily adapt this to show different customer names instead of numbers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...