user550738
user550738

Reputation:

how to add an image to my header in iText generated PDF?

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

Upvotes: 5

Views: 31527

Answers (5)

Kuzon
Kuzon

Reputation: 36

First of all you need to convert your image to base64 and define it.

string base64Image = @"your_image_base64_code";

Then we converted the image into bytes

byte[] imageBytes = Convert.FromBase64String(base64Image);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageBytes);

We need to adjust the position of the image on the page

 image.SetAbsolutePosition(positionX, positionY);//You must enter a float type value according to the x and y coordinates.
 image.ScaleAbsoluteHeight(40);//image height
 image.ScaleAbsoluteWidth(80); //image width           
 document.Add(image);

For more examples, you can visit itextpdf page

Upvotes: 0

Mohit Singh
Mohit Singh

Reputation: 6167

A generic solution to add image at the top of the page. We can do it by positing image to the top also. it may fix your requirement

public static void main(String[] args) throws MalformedURLException, IOException, DocumentException {
      Document document = new Document();
        try {
            PdfWriter.getInstance(document,
                    new FileOutputStream("HelloWorld.pdf"));
            document.open();

            //
            // Scale the image to a certain percentage
            //
            String filename = "image.jpg";
            Image image = Image.getInstance(filename);
            image = Image.getInstance(filename);
            image.scalePercent(200f);
            image.setAbsolutePosition(0, (float) (PageSize.A4.getHeight() - 20.0));
            System.out.println(image.getScaledHeight());
            document.add(image);

            //
            // Scales the image so that it fits a certain width and
            // height
            //
            image.scaleToFit(100f, 200f);
            document.add(image);
            document.add(new Chunk("This is chunk 3. "));
            System.out.println("created");
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
}

}

Upvotes: 0

Sericaia
Sericaia

Reputation: 450

I've set abolute positions and alignment to the image (in this case I placed my image in the header)

    try {
        Image img = Image.getInstance("url/logo.png");
        img.scaleToFit(100,100);  
        img.setAbsolutePosition((rect.getLeft() + rect.getRight()) / 2 - 45, rect.getTop() - 50);
        img.setAlignment(Element.ALIGN_CENTER);          
        writer.getDirectContent().addImage(img);
      } catch (Exception x) {
        x.printStackTrace();
      }

I've also adjusted the the document margins in order to have delimited space in the header and footer of the document.

document.setMargins(20, 20, 100, 100);

Upvotes: 0

Bruno Lowagie
Bruno Lowagie

Reputation: 77528

You are making two major mistakes.

  1. You are creating a new instance of the object for every new page. This will result in a bloated PDF as the image bytes will be added as many times as there as pages. Please create the Image object outside the onEndPage() method, and reuse it. This way, the image bytes will be added to the PDF only once.
  2. As documented, the Document passed to the onEndPage() 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 with new Document(PageSize.A4, 36, 36, 154, 54). In reality, it's an instance of a PdfDocument class created internally by the PdfWriter instance. To add an image, you need to get the PdfContentByte from the writer, and add the image using addImage().

Errors like this can easily be avoided by reading the documentation. You can save plenty of time by reading my book iText in Action.

Upvotes: 11

Can you try

img.setAbsolutePosition(10, 10);
writer.getDirectContent().addImage(img);

instead of

document.add(img);

inside onPageEnd?

Upvotes: 4

Related Questions