使用iTextSharp设置图像位置
问题描述:
我在纸张大小的页面方向上有问题。
我有一个pdf文件,其中包含肖像和风景页面。使用iTextSharp设置图像位置
此代码完美工作。
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);
因为我使用绝对值设置图像位置。
img.SetAbsolutePosition(250,300);
如果页面是横向或纵向,T如何设置图像位置?
注意:一个PDF与横向和纵向页面方向。
是否有机会可以使用if语句?
if (//paper is landscape)
{
//code here
}
else
{
//code here
}
答
你想要什么来实现呢?
通常,iText会考虑页面旋转的值。这意味着当页面旋转时,坐标也会旋转。
如果你想否决此,您可以加入这一行:
stamper.RotateContents = false;
这在Chapter 6 of my book解释。你可以尝试this example看出区别:
- 没有旋转,文本添加正常:hello1.pdf
- 旋转,文本通常添加(=旋转):hello2.pdf
- 旋转,文本添加旋转忽略:hello3.pdf
当然,这里假定为页面定义了一个旋转。有时,通过定义不同的页面大小而不是定义旋转来模拟景观。
在这种情况下,您还应该阅读Chapter 6,因为它解释了如何获取文档的MediaBox。请参阅示例PageInformation,该示例介绍了诸如GetPageSize()
,GetRotation()
和GetPageSizeWithRotation()
等方法。
这是所有记录,但如果它不回答你的问题,请澄清。如示例中所示,添加新内容时默认会考虑轮换,所以也许我误解了这个问题。