Why does the following code affect a page's ability to find its top, bottom, right and left?
Before applying it, reader.GetCropBox(i).GetLeft(0)
and reader.GetPageSize(i).GetLeft(0)
return the far left point of every page in an assorted set. After applying it, GetLeft(0)
is the far left on some pages and on others the left most point AFTER the margin ends.
I'm trying to create a header on any given set of preexisting pages (ie, create white space and then put text in it)
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);
}
//////////
}
}
}
}
The original code is borrowed from the answer given here: How to resize existing pdf page size