简体   繁体   中英

How to add Header and footer to my PDF using Itext in java

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

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);
}
 HeaderFooter event = new HeaderFooter();
  writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));
  writer.setPageEvent(event);

document itxt

ejemplo example of PDF

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).

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);

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);
  }
}
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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM