13

I want to add a header image and page numbers as footer to my PDF file. How can I add header and footer to my PDF file using Itext?

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Header;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
new Demo().createPDF();
}
public void createPDF(){
Document document = new Document (PageSize.A4);
try {
PdfWriter.getInstance(document, new FileOutputStream("C:/Documents and Settings/mnavya/Desktop/AddImage.pdf"));
document.open ();
document.addCreator("Binod by Demo.java");
document.addAuthor("Binod Suman");
document.addTitle("First PDF By Binod");
Image image = Image.getInstance("https://snaplogic-h.s3.amazonaws.com/uploads/partner/logo/24/stratappa.jpg?u=1382443264");
image.scaleAbsolute(50,50);
document.add(image);

Paragraph paragraph = new Paragraph(
        " Factors",new Font(Font.FontFamily.HELVETICA, 25));
document.add(paragraph);
document.add(Chunk.SPACETABBING);

PdfPTable table = new PdfPTable(8);
table.setWidthPercentage(100);
float[] columnWidths = new float[] { 7, 20, 9, 9, 9, 9, 5, 3 };
table.setWidths(columnWidths);

PdfPCell cell = new PdfPCell();
cell.setColspan(8);
cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
table.addCell(cell);
table.addCell(" ");
table.addCell(" ");
table.addCell("");
table.addCell("");
table.addCell("%");
table.addCell("");
table.addCell(" ");
table.addCell(" ");
document.add(table);
document.close ();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
System.out.println("******** PDF Created ***************");
}
}
Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58
Navyah
  • 1,660
  • 10
  • 33
  • 58
  • Have a look at [this answer](http://stackoverflow.com/questions/17214756/how-to-add-header-and-footer-in-dynamic-pdf-using-itextlibrary/17217346#17217346) to [How to add Header and Footer in dynamic pdf using iTextLibrary](http://stackoverflow.com/questions/17214756/how-to-add-header-and-footer-in-dynamic-pdf-using-itextlibrary). – mkl Nov 08 '13 at 11:43

6 Answers6

23

Footer Header utils:

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;

public class HeaderFooterPageEvent extends PdfPageEventHelper {

    public void onStartPage(PdfWriter writer, Document document) {
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("Top Left"), 30, 800, 0);
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("Top Right"), 550, 800, 0);
    }

    public void onEndPage(PdfWriter writer, Document document) {
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("http://www.xxxx-your_example.com/"), 110, 30, 0);
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("page " + document.getPageNumber()), 550, 30, 0);
    }

}

Use HeaderFooterPageEvent:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
Document document = new Document(PageSize.A4, 20, 20, 50, 25);
PdfWriter writer = PdfWriter.getInstance(document, baos);
HeaderFooterPageEvent event = new HeaderFooterPageEvent();
writer.setPageEvent(event);

EDIT (add image sample):

public void onStartPage(PdfWriter writer, Document document) {
    String img = APPLICATION_SERVER_ROOT_PATH + File.separator + "assets" + File.separator + "images" + File.separator + "logo-tp-white.png";
    Image image;
    try {
        image = Image.getInstance(img);
        image.setAlignment(Element.ALIGN_RIGHT);
        image.setAbsolutePosition(20, 790);
        image.scalePercent(7.5f, 7.5f);
        writer.getDirectContent().addImage(image, true);
    } catch (IOException | DocumentException e) {
        log.error("L'image logo-tp-50x50.png a provoqué une erreur.", e);
    }

    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(""), 30, 800, 0);
    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(Constants.GLOBAL_HOST + " pour réussir votre prochain concours."), 400, 800, 0);
}
Stéphane GRILLON
  • 11,140
  • 10
  • 85
  • 154
  • Any way to add images on header/footer – charle819 Oct 04 '18 at 09:37
  • Does this also work for `PDFAWriter` or is there any change required? I am not able to use this for PDF/A-2 – S_S Nov 12 '18 at 10:24
  • @Sumit, I think so because `PdfAWriter` extends `PdfWriter` (http://itextsupport.com/apidocs/itext5/5.5.9/com/itextpdf/text/pdf/PdfAWriter.html) – Stéphane GRILLON Nov 12 '18 at 11:17
  • @sgrillon I am getting the exception related to font not being embedded in `new Phrase()`, is there any method to add a `paragraph` or set `font` of phrase as an embedded font? – S_S Nov 13 '18 at 06:17
4
 HeaderFooter event = new HeaderFooter();
  writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));
  writer.setPageEvent(event);

document itxt

ejemplo example of PDF

3

Please take a look at the official iText documentation before posting a question on StackOverflow. More specifically: check the examples for the keyword header / footer.

You'll find the MovieCountries1 example that creates a PDF with a header that has page numbers Page 1 / 39, Page 2 / 39, etc.

Use that example as inspiration. If you don't need a Page X of Y header (or footer). You can use a more simple example, such as the one in the answer to How to add Header and Footer in dynamic pdf using iTextLibrary? (which was also inspired by one of the examples of my book).

Community
  • 1
  • 1
Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
  • 8
    Example is appreciated, but remember linkrot and why [link only answers aren't really good answers](http://meta.stackexchange.com/q/8231/273645). – TT. Nov 30 '16 at 12:19
2

I am using iText2. Although PdfPageEventHelper can solve it, HeaderFooter seems more easier. Make sure add HeaderFooter before document.open(), otherwise first page will not display it.

Document document = new Document(PageSize.A4, MARGIN, MARGIN, MARGIN, MARGIN);
HeaderFooter footer = new HeaderFooter(new Phrase("- "), new Phrase(" -"));
footer.setAlignment(Element.ALIGN_CENTER);
footer.setBorder(Rectangle.NO_BORDER);
document.setFooter(footer);
Qingyu Yan
  • 31
  • 3
2

This may help you for adding header and footer using itext :

public class PageNumber  extends PdfPageEventHelper{
private PdfTemplate t;
private Image total;

public void onOpenDocument(PdfWriter writer, Document document) {
    t = writer.getDirectContent().createTemplate(30, 16);
    try {
        total = Image.getInstance(t);
        total.setRole(PdfName.ARTIFACT);
    } catch (DocumentException de) {
        throw new ExceptionConverter(de);
    }
}

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

private void addHeader(PdfWriter writer){
    PdfPTable header = new PdfPTable(1);
    try {
        // set defaults
        header.setWidths(new int[]{100});
        header.setTotalWidth(525);
        header.setLockedWidth(true);
        header.getDefaultCell().setFixedHeight(65);
        header.getDefaultCell().setBorder(Rectangle.BOTTOM);
        header.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY);

        // add image
        Image logo = Image.getInstance(PageNumber.class.getResource("/sample.png"));
        header.addCell(logo);


        // write content
        header.writeSelectedRows(0, -1, 34, 823, writer.getDirectContent());
    } catch(DocumentException de) {
        throw new ExceptionConverter(de);
    } catch (MalformedURLException e) {
        throw new ExceptionConverter(e);
    } catch (IOException e) {
        throw new ExceptionConverter(e);
    }
}


private void addFooter(PdfWriter writer){
    PdfPTable footer = new PdfPTable(1);
    try {

        footer.setWidths(new int[]{100});
        footer.setTotalWidth(527);
        footer.setLockedWidth(false);
        footer.getDefaultCell().setFixedHeight(40);
        footer.getDefaultCell().setBorder(Rectangle.TOP);
        footer.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY);

        // add current page count
        footer.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
        footer.addCell(new Phrase(String.format( writer.getPageNumber()+ " | Page") , new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD)));

        // write page
        PdfContentByte canvas = writer.getDirectContent();
        canvas.beginMarkedContentSequence(PdfName.ARTIFACT);
        footer.writeSelectedRows(0, -1, 34, 50, canvas);
        canvas.endMarkedContentSequence();
    } catch(DocumentException de) {
        throw new ExceptionConverter(de);
    }
}

public void onCloseDocument(PdfWriter writer, Document document) {
    int totalLength = String.valueOf(writer.getPageNumber()).length();
    int totalWidth = totalLength * 5;
    ColumnText.showTextAligned(t, Element.ALIGN_LEFT,
            new Phrase(String.valueOf(writer.getPageNumber()),new Font(Font.FontFamily.HELVETICA, 12)),
            totalWidth, 6, 0);
  }
}
Gilles-Antoine Nys
  • 1,481
  • 16
  • 21
  • Your answer essentially uses the same technique as the earlier, accepted answer. In which way does your answer exceed that answer? – mkl Dec 10 '18 at 11:57
  • yeah your right., but i thought that it will also help me that any new suggestion regarding this . – Yahini priya Raja Dec 10 '18 at 12:11
0
HeaderFooter header =new HeaderFooter(new Phrase(resources.getMessage("your header")),false);
                header.setAlignment(HeaderFooter.ALIGN_CENTER);
                header.setBorder(Rectangle.NO_BORDER);
                document.setHeader(header);
                document.open();