I’m using iText to generate a PDF. I created a custom PdfPageEventHelper to add a header (and footer) to each page.
My problem is I don’t know how to add the image so it is displayed in the “header box”. I only know how to add the image to the document content itself (if that makes sense).
Here’s some code snippets …
public static void main(String[] args) {
Rectangle headerBox = new Rectangle(36, 54, 559, 788);
/* ... */
Document document = new Document(PageSize.A4, 36, 36, 154, 54);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FILENAME));
HeaderFooter event = new HeaderFooter();
writer.setBoxSize("headerBox", headerBox);
writer.setPageEvent(event);
document.open();
addContent();
document.close();
}
static class HeaderFooter extends PdfPageEventHelper {
public void onEndPage(PdfWriter writer, Document document) {
Rectangle rect = writer.getBoxSize("headerBox");
// add header text
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_RIGHT, new Phrase("Hello", fontHeader1),
rect.getLeft(), rect.getTop(), 0);
// add header image
try {
Image img = Image.getInstance("c:/mylogo.PNG");
img.scaleToFit(100,100);
document.add(img);
} catch (Exception x) {
x.printStackTrace();
}
}
}
Any suggestions on the appropriate way to add the image to the header are greatly appreciated!!
Rob
You are making two major mistakes.
Imageobject outside theonEndPage()method, and reuse it. This way, the image bytes will be added to the PDF only once.Documentpassed to theonEndPage()method as a parameter should be considered as a read-only parameter. It is forbidden to add content to it. It’s a different object than the one you created withnew Document(PageSize.A4, 36, 36, 154, 54). In reality, it’s an instance of aPdfDocumentclass created internally by thePdfWriterinstance. To add an image, you need to get thePdfContentBytefrom the writer, and add the image usingaddImage().Errors like this can easily be avoided by reading the documentation. You can save plenty of time by reading my book iText in Action.