itextsharp PdfCopy and landscape pages
- by Andreas Rehm
I'm using itextsharp to join mutiple pdf documents and add a footer.
My code works fine - except for landscape pages - it isn't detecting the page rotation - the footer is not centerd for landscape:
public static int AddPagesFromStream(Document document, PdfCopy pdfCopy, Stream m, bool addFooter, int detailPages, string footer, int footerPageNumOffset, int numPages, string pageLangString, string printLangString)
{
CreateFont();
try
{
m.Seek(0, SeekOrigin.Begin);
var reader = new PdfReader(m);
// get page count
var pdfPages = reader.NumberOfPages;
var i = 0;
// add pages
while (i < pdfPages)
{
i++;
// import page with pdfcopy
var page = pdfCopy.GetImportedPage(reader, i);
// get page center
float posX;
float posY;
var rotation = page.BoundingBox.Rotation;
if (rotation == 0 || rotation == 180)
{
posX = page.Width / 2;
posY = 0;
}
else
{
posX = page.Height / 2;
posY = 20f;
}
var ps = pdfCopy.CreatePageStamp(page);
var cb = ps.GetOverContent();
// add footer
cb.SetColorFill(BaseColor.WHITE);
var gs1 = new PdfGState {FillOpacity = 0.8f};
cb.SetGState(gs1);
cb.Rectangle(0, 0, document.PageSize.Width, 46f + posY);
cb.Fill();
// Text
cb.SetColorFill(BaseColor.BLACK);
cb.SetFontAndSize(baseFont, 7);
cb.BeginText();
// create text
var pages = string.Format(pageLangString, i + footerPageNumOffset, numPages);
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, printLangString, posX, 40f + posY, 0f);
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, footer, posX, 28f + posY, 0f);
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, pages, posX, 20f + posY, 0f);
cb.EndText();
ps.AlterContents();
// add page to new pdf
pdfCopy.AddPage(page);
}
// close PdfReader
reader.Close();
// return number of pages
return i;
}
catch (Exception e)
{
Console.WriteLine(e);
return 0;
}
}
How do I detect the page rotation (e.g. landscape) format in this case? The given example works for PdfReader but not for PdfCopy.
Edit:
Why do I need PdfCopy? I tried copying a word pdf export. Some word hyperlinks will not work when you try to copy pages with PdfReader. Only PdfCopy transfers all needed page informations.
Edit: (SOLVED)
You need to use reader.GetPageRotation(i);