'Setting image position using iTextSharp

I have a problem with regards on the page orientation of the paper size.
I have a pdf file which contains portrait and landscape page.

this code works perfectly.

string FileLocation = "c:\\Temp\\SomeFile.pdf";
string WatermarkLocation = "c:\\Temp\\watermark.gif";
Document document = new Document();
PdfReader pdfReader = new PdfReader(FileLocation);
PdfStamper stamp = new PdfStamper(pdfReader, new FileStream(FileLocation.Replace(".pdf","[temp][file].pdf"), FileMode.Create));

iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(WatermarkLocation);
img.SetAbsolutePosition(250,300); // set the position in the document where you want the watermark to appear (0,0 = bottom left corner of the page)

PdfContentByte waterMark;
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
    waterMark = stamp.GetUnderContent(page);
    waterMark.AddImage(img);
}
stamp.FormFlattening = true;
stamp.Close();

// now delete the original file and rename the temp file to the original file
File.Delete(FileLocation);
File.Move(FileLocation.Replace(".pdf", "[temp][file].pdf"), FileLocation);

since I'm using absolute value to set the image position.

img.SetAbsolutePosition(250,300);

How can T set the image position if the page is landscape or portrait?
note: One pdf with landscape and portrait page orientation.

Is there by chance that I can use if statement?

if (//paper is landscape)
{
    //code here
}
else 
{
    //code here
}


Solution 1:[1]

What do you want to achieve?

Normally, iText takes into account the value of the page rotation. This means that when a page is rotated, the coordinates will be rotated too.

If you want to overrule this, you can add this line:

stamper.RotateContents = false;

This is explained in Chapter 6 of my book. You can try this example to see the difference:

  1. No rotation, text added normally: hello1.pdf
  2. Rotation, text added normally ( = rotated): hello2.pdf
  3. Rotation, text added with rotation ignored: hello3.pdf

Of course, this assumes that a rotation was defined for the pages. Sometimes, landscape is mimicked by defining a different page size instead of defining a rotation.

In that case, you should also read Chapter 6 because it explains how to get the MediaBox of a document. see the example PageInformation that introduces methods such as GetPageSize(), GetRotation() and GetPageSizeWithRotation().

This is all documented, but if it doesn't answer your question, please clarify. As demonstrated in the example, the rotation is taken into account by default when adding new content, so maybe I misunderstood the question.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bruno Lowagie