Reputation: 2715
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.
Upvotes: 0
Views: 3446
Reputation: 77528
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!
Upvotes: 1