0

I have an existing PDF in which i am trying to add a logo in Header, I have found a good example from
How can I insert an image with iTextSharp in an existing PDF?

It is adding logo in Footer passing 0,0 in image.SetAbsolutePosition(100, 100); but i want to add logo in Header. If anyone know about it, please suggest.

Community
  • 1
  • 1
donstack
  • 2,557
  • 3
  • 29
  • 44

1 Answers1

1

Are you creating the document from scratch?

If so, you know the dimensions of the page. It's PageSize.A4 by default, or whatever Rectangle you passed to the Document constructor. You need to adjust the X and Y values depending on the value of that Rectangle. For instance:

image.setAbsolutePosition(rect.Left, rect.Top - image.ScaledHeight);

Where rect is the page size.

As you're adding a header, you want this header to appear on each page, hence you'll use a page event. Take a look at the OnEndPage() method in this example. Make sure you don't add the image bytes as many times as there are pages! Create the image instance outside the onEndPage method, for instance in the constructor of your page event implementation.

If not, you need to get the CropBox of every page:

rect = reader.GetCropBox(page);

If no CropBox was defined, you need to get the MediaBox:

rect = reader.GetPageSize(page);

Where page is a page number (e.g. 1). Based on the value of rect, you can define the position of the image, as shown above.

I hope you understand that your code where you've used x = 0 and y = 0 won't always show the image in the footer. You're making the assumption that the lower-left corner of each page in each PDF has the coordinate (0, 0). That assumption is wrong!

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
  • ok, this if fine, do you have any idea of PageEvent which is more efficient way to add header/footer – donstack Aug 23 '13 at 13:20
  • I'm the original developer of iText, so... yes, I have plenty of ideas about `PageEvent`. Unfortunately, I'm not smart enough to understand your question :-( – Bruno Lowagie Aug 23 '13 at 13:22
  • sorry for not being clear, If PDF is of thousands pages then above code of adding header on each page will take very much time, so is there is any efficient way to do this. I have heard of PageEvent somewhere i will give you link if you want – donstack Aug 23 '13 at 13:27
  • Read my answer! Are you creating a PDF from scratch? Then use page events. Are you adding a header to an existing PDF? Then using page events is impossible! – Bruno Lowagie Aug 23 '13 at 13:39
  • Ok, i think PageEvent is used when creating a new PDF http://kuujinbo.info/cs/itext_img_hdr.aspx – donstack Aug 23 '13 at 13:39
  • 2
    Didn't you notice that I'm the author of the book "iText in Action" of which you can find the examples on the site you're referring to? http://kuujinbo.info/iTextInAction2Ed/index.aspx ;-) – Bruno Lowagie Aug 23 '13 at 13:41