Image Positioning Using iTextSharp

I have a problem with the orientation of the page to fit the paper.
I have a PDF file that contains a book and landscape page.

this code works fine.

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 am using an absolute value to set the position of the image.

 img.SetAbsolutePosition(250,300); 

How can I set the image position if the page is horizontal or portrait?
Note : one PDF file with landscape and landscape page orientation.

Can I accidentally use an if statement?

 if (//paper is landscape) { //code here } else { //code here } 
+6
source share
1 answer

What do you want to achieve?

Typically, iText takes into account the value of page rotation. This means that when you rotate the page, the coordinates will also be rotated.

If you want to undo 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:

  • No rotation, the text is added normally: hello1.pdf
  • Rotation, the text is added normally (= rotated): hello2.pdf
  • Rotate, text added ignoring rotation: hello3.pdf

Of course, this assumes that rotation has been defined for the pages. Sometimes a landscape mimics by defining a different page size rather than defining a rotation.

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

All this is documented, but if it does not answer your question, please clarify. As the example shows, rotation is taken into account by default when adding new content, so maybe I did not understand this question.

+1
source

Source: https://habr.com/ru/post/943940/


All Articles