1
votes

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);
2

2 Answers

0
votes

With PDFsharp up to version 1.50 beta 3b there is a known problem when opening PDF files that have pages in landscape format. I'd recommend removing three lines as shown in this post on the PDFsharp forum:
http://forum.pdfsharp.net/viewtopic.php?p=9591#p9591
Simply do nothing inside internal PdfPage(PdfDictionary dict). I recommend downloading the source package, referencing the C# projects in your solution, and making the change to the code.

When swapping width and height of the rectangle, make sure you also update the center of the rotation in the call of RotateAtTransform.

0
votes

Change

sf.LineAlignment = XLineAlignment.Far;

to

sf.LineAlignment = XLineAlignment.Center;

Your text is now vertical in the center of the page. You can then use

xg.TranslateTransform(0, xg.PageSize.Width / 2);

to move the text to the side.