C# iTextSharp-创建页眉/页边距会导致页面坐标不一致
为什么以下代码会影响页面查找其顶部、底部、右侧和左侧的能力 在应用它之前,C# iTextSharp-创建页眉/页边距会导致页面坐标不一致,c#,itext,C#,Itext,为什么以下代码会影响页面查找其顶部、底部、右侧和左侧的能力 在应用它之前,reader.GetCropBox(i).GetLeft(0)和reader.GetPageSize(i).GetLeft(0)返回组合集中每个页面的最左侧点。应用它之后,GetLeft(0)在某些页面上是最左边的,在其他页面上是页边结束后最左边的点 我试图在任何给定的一组预先存在的页面上创建一个标题(即,创建空白,然后将文本放入其中) 使用(Stream-Stream=newfilestream(outputPdfPat
reader.GetCropBox(i).GetLeft(0)
和reader.GetPageSize(i).GetLeft(0)
返回组合集中每个页面的最左侧点。应用它之后,GetLeft(0)
在某些页面上是最左边的,在其他页面上是页边结束后最左边的点
我试图在任何给定的一组预先存在的页面上创建一个标题(即,创建空白,然后将文本放入其中)
使用(Stream-Stream=newfilestream(outputPdfPath2,System.IO.FileMode.Create))
{
使用(PdfReader读取器=新PdfReader(outputPdfPath))
{
使用(PdfStamper压模=新PdfStamper(读卡器,流))
{
int n=reader.NumberOfPages;
对于(int i=1;i公差| | Math.Abs(heightToAdd)>公差)
{
float[]newBoxValues=新的float[]{
cropBox.Left-marginLeft,//宽度添加/2,
cropBox.Bottom-marginBottom,//添加高度/2,
cropBox.Right+marginRight,//宽度添加/2,
cropBox.顶部+边缘顶部//添加高度/2
};
PdfArray newBox=新的PdfArray(newBox值);
PdfDictionary pDict=reader.GetPageN(i);
pDict.Put(PdfName.CROPBOX,newBox);
pDict.Put(PdfName.MEDIABOX,newBox);
}
//////////
}
}
}
}
原始代码借用了此处给出的答案:能否与您的代码一起共享一个说明问题的PDF?我发现了问题。。。有些页面是旋转的,直到你意识到GetPageSize和GetCropBox都返回了一个不是旋转的旋转,你才知道这一点。。。
using (Stream stream = new FileStream(outputPdfPath2, System.IO.FileMode.Create))
{
using (PdfReader reader = new PdfReader(outputPdfPath))
{
using (PdfStamper stamper = new PdfStamper(reader, stream))
{
int n = reader.NumberOfPages;
for (int i = 1; i <= n; i++)
{
//iTextSharp.text.Rectangle size = reader.GetPageSize(i);
iTextSharp.text.Rectangle size = reader.GetCropBox(i);
//////////
// Create Margin
float marginTop = 160;
float marginBottom = 160;
float marginLeft = 160;
float marginRight = 160;
float width = size.Width + marginLeft + marginRight; // 8.5f * 72;
float height = size.Height + marginTop + marginBottom; // 11f * 72;
float tolerance = 1f;
iTextSharp.text.Rectangle cropBox = reader.GetCropBox(i);
float widthToAdd = width - cropBox.Width;
float heightToAdd = height - cropBox.Height;
if (Math.Abs(widthToAdd) > tolerance || Math.Abs(heightToAdd) > tolerance)
{
float[] newBoxValues = new float[] {
cropBox.Left - marginLeft, // widthToAdd / 2,
cropBox.Bottom - marginBottom,// heightToAdd / 2,
cropBox.Right + marginRight, // widthToAdd / 2,
cropBox.Top + marginTop // heightToAdd / 2
};
PdfArray newBox = new PdfArray(newBoxValues);
PdfDictionary pDict = reader.GetPageN(i);
pDict.Put(PdfName.CROPBOX, newBox);
pDict.Put(PdfName.MEDIABOX, newBox);
}
//////////
}
}
}
}