Given any existing PDF with many various page sizes and orientations, my program must place a single line of text in the center of each of the four edges on the page, rotated for that page edge. I am using PDFsharp with C#.
For the bottom of the page, I don't need any text rotation and it works great:
// Font for added margin text.
XFont xf = new XFont("Arial", 10, XFontStyle.Bold);
// String format to place at bottom center.
XStringFormat sf = new XStringFormat();
sf.Alignment = XStringAlignment.Center;
sf.LineAlignment = XLineAlignment.Far;
using (PdfDocument pdfdOut = new PdfDocument())
{
using (PdfDocument pdfdIn = PdfReader.Open(sInPdfPath, PdfDocumentOpenMode.Import))
for (int iInPageNo = 0; iInPageNo < pdfdIn.PageCount; iInPageNo++)
{
PdfPage pdfpOut = pdfdOut.AddPage(pdfdIn.Pages[iInPageNo]);
using (XGraphics xg = XGraphics.FromPdfPage(pdfpOut, XGraphicsPdfPageOptions.Append))
{
XRect xr = pdfpOut.MediaBox.ToXRect();
xg.DrawString("Bottom Centered Text", xf, XBrushes.Red, xr, sf);
}
} // for iInPageNo, using pdfdIn
// ...save the output PDF here...
} // using pdfdOut
When I attempt to place vertical text centered on the left side of the page, it goes off page for portrait pages and is too far from the edge for landscape pages:
using (XGraphics xg = XGraphics.FromPdfPage(pdfpOut, XGraphicsPdfPageOptions.Append))
{
// Rotate graphics 90 degrees around the center of the page.
xg.RotateAtTransform(90, new XPoint(xg.PageSize.Width / 2d, xg.PageSize.Height / 2d));
XRect xr = pdfpOut.MediaBox.ToXRect();
xg.DrawString("Left Centered Text", xf, XBrushes.Red, xr, sf);
}
I reasoned that the XRect needed to have its Width and Height swapped, but I never see my Left Centered Text when I do that:
XRect xr = New XRect(pdfpOut.MediaBox.ToXRect().Height, pdfpOut.MediaBox.ToXRect().Width);
The MediaBox has the same dimensions as the PageSize.
For testing I have displayed the XRect, to know what's going on. But I just can't get it to look the same with rotation as without rotation:
xg.DrawRectangle(XPens.Red, xr);