问题
I have been trying to position a Text Water marks on PDF file using iTextSharp and i am struggling to find the coordinates on each page. it works fine when all the pages in pdf file are of same rotation but if the rotation is different then the coordinates are completely different.
PdfImportedPage page = stamper.GetImportedPage(pdfReader, i);
var rotationValue = page.Rotation;
and to add the watermark
cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "This is WaterMark 1", 20, 20, 90f);
this code is unable to find the X and Y position on the page. how can i get the exact location where i want to add the watermark?
回答1:
This question is answered in an article written in French that was based on several StackOverflow questions I answered in English: Comment créer un filigrane transparent en PDF?
The questions this blog post was based on, are:
- How to watermark PDFs using text or images? (This is an important one for you, because it deals with page rotations!)
- How to add a watermark to a PDF file?
- How to extend the page size of a PDF to add a watermark?
These questions and their answers can be found in The Best iText Questions on StackOverflow, a free ebook that can be downloaded from the iText site. It also contains a couple of answers that were never published on StackOverflow.
You shouldn't import the page to find out the rotation. There are other ways to get that information. You'll notice that you can use the getPageSize()
and the GetPageSizeWithRotation()
methods depending on whether or not you want to get the page size along with the rotation (there's also a GetRotation()
method).
Furthermore, you should experiment with the RotateContents
property:
stamper.RotateContents = false;
It is not exactly clear to me whether or not you want the watermark to follow or ignore the rotation, but the GetPageSize()
and the GetPageSizeWithRotation()
method, you'll be able to avoid having to use hard-coded values such as x = 20; y = 20
(as done in your code snippet). If you want the middle coordinate of page i
, you can use this code:
Rectangle pagesize = reader.GetPageSizeWithRotation(i);
x = (pagesize.Left + pagesize.Right) / 2;
y = (pagesize.Top + pagesize.Bottom) / 2;
来源:https://stackoverflow.com/questions/30798383/get-exact-cordinates-of-the-page-to-add-a-watermark-with-different-page-rotation