How to add Header and Footer in dynamic pdf using iTextLibrary?

送分小仙女□ 提交于 2019-12-28 18:42:10

问题


I have created a PDF file dynamically using iText Library, Now I want to add Header and Footer in PDF's pages, for this one I have added given code:

document.addHeader("My Header Title", "My Header Details");

But in my PDF's pages this header couldn't set. What is issue that I don't know, If you have any idea related to it,please share your thoughts.


回答1:


In case you use a current iText version (i.e. 5.4.x as of now) have a look at the sample MovieHistory2 from iText in Action — 2nd Edition which shows how to add headers (different ones for odd and even pages) to a PDF while creating it.

Most essential is a PdfPageEventHelper implementation

/** Inner class to add a header and a footer. */
class HeaderFooter extends PdfPageEventHelper {
    /** Alternating phrase for the header. */
    Phrase[] header = new Phrase[2];
    /** Current page number (will be reset for every chapter). */
    int pagenumber;

    /**
     * Initialize one of the headers.
     * @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(
     *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
     */
    public void onOpenDocument(PdfWriter writer, Document document) {
        header[0] = new Phrase("Movie history");
    }

    /**
     * Initialize one of the headers, based on the chapter title;
     * reset the page number.
     * @see com.itextpdf.text.pdf.PdfPageEventHelper#onChapter(
     *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document, float,
     *      com.itextpdf.text.Paragraph)
     */
    public void onChapter(PdfWriter writer, Document document,
            float paragraphPosition, Paragraph title) {
        header[1] = new Phrase(title.getContent());
        pagenumber = 1;
    }

    /**
     * Increase the page number.
     * @see com.itextpdf.text.pdf.PdfPageEventHelper#onStartPage(
     *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
     */
    public void onStartPage(PdfWriter writer, Document document) {
        pagenumber++;
    }

    /**
     * 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);
    }
}

which is registered like this:

    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
    HeaderFooter event = new HeaderFooter();
    writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));
    writer.setPageEvent(event);

EDIT: As requested in the comments, a simpler variant of the onEndPage method with a static header instead of the alternating one:

    public void onEndPage(PdfWriter writer, Document document)
    {
        Rectangle rect = writer.getBoxSize("art");
        ColumnText.showTextAligned(writer.getDirectContent(),
                Element.ALIGN_RIGHT, new Phrase("My static header text"),
                rect.getRight(), rect.getTop(), 0);
        ColumnText.showTextAligned(writer.getDirectContent(),
                Element.ALIGN_CENTER, new Phrase(String.format("page %d", pagenumber)),
                (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0);
    }



回答2:


please refer this site.......

https://www.coderanch.com/how-to/java/ItextExample




回答3:


Please first refer to the accepted answer of this question.
That answer is very helpful (and It helped me to).
Just in case you are programming in C#, here is the SAME accepted answer but in C# version

/// <summary>
/// Inner class to add a header and a footer.
/// </summary>
internal class HeaderFooter : PdfPageEventHelper
{
    private Phrase[] header = new Phrase[2];
    private int pageNumber;

    public override void OnOpenDocument(PdfWriter writer, Document document)
    {
        header[0] = new Phrase("Smares in Header");
    }

    public override void OnChapter(PdfWriter writer, Document document, float paragraphPosition, Paragraph title)
    {
        header[1] = new Phrase(title.Content);
        pageNumber = 1;
    }

    public override void OnStartPage(PdfWriter writer, Document document)
    {
        pageNumber++;
    }

    public override void OnEndPage(PdfWriter writer, Document document)
    {
        Rectangle rect = writer.GetBoxSize("art");
        switch (writer.PageNumber % 2)
        {
            case 0:
                ColumnText.ShowTextAligned(writer.DirectContent,
                        Element.ALIGN_RIGHT, header[0],
                        rect.Right, rect.Top, 0);
                break;
            case 1:
                ColumnText.ShowTextAligned(writer.DirectContent,
                        Element.ALIGN_LEFT, header[1],
                        rect.Left, rect.Top, 0);
                break;
        }

        ColumnText.ShowTextAligned(writer.DirectContent,
                Element.ALIGN_CENTER, new Phrase(String.Format("page {0}", pageNumber)),
                (rect.Left + rect.Right) / 2, rect.Bottom - 18, 0);
    }
}

and the registration of the event will be :

using (MemoryStream ms = new MemoryStream())
{
    using (Document doc = new Document(PageSize.A4, -30, -30, 45, 45))
    {
        using (PdfWriter writer = PdfWriter.GetInstance(doc, ms))
        {
             HeaderFooter ev = new HeaderFooter();
             writer.SetBoxSize("art", new Rectangle(36, 54, 559, 788));
             writer.PageEvent = ev;

             // continue your code here 
        }
    }
}

NOTE : this is just a conversion of the accepted answer from java to C#. but you can customize this according to your needs, as I did with it.




回答4:


You can add like that

HeaderFooter header = new HeaderFooter(new Phrase("Add Header Part Here"), false);  
HeaderFooter footer = new HeaderFooter(new Phrase("Add Footer Here"), new Phrase("."));  

document.setHeader(header);  
document.setFooter(footer); 


来源:https://stackoverflow.com/questions/17214756/how-to-add-header-and-footer-in-dynamic-pdf-using-itextlibrary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!