PDFsharp页面

时间:2017-03-13 20:45:27

标签: pdf pdfsharp margins

鉴于任何现有的PDF具有许多不同的页面大小和方向,我的程序必须在页面的四个边缘的每个边缘的中心放置一行文本,并针对该页面边缘旋转。我正在使用带有C#的PDFsharp。

对于页面底部,我不需要任何文字轮换,效果很好:

// 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

当我尝试将垂直文本放在页面左侧的中心位置时,它会离开页面以查看纵向页面,并且与横向页面的边缘相距太远:

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

我推断XRect需要交换宽度和高度,但是当我这样做时,我从未看到过我的左中心文本:

XRect xr = New XRect(pdfpOut.MediaBox.ToXRect().Height, pdfpOut.MediaBox.ToXRect().Width);

MediaBox与PageSize具有相同的尺寸。

为了测试我已经展示了XRect,以了解正在发生的事情。但是我不能让它看起来像旋转一样没有旋转:

xg.DrawRectangle(XPens.Red, xr);

2 个答案:

答案 0 :(得分:0)

使用PDFsharp版本高达1.50 beta 3b时,打开包含横向格式页面的PDF文件时会出现一个已知问题。我建议删除三行,如PDFsharp论坛上的这篇文章所示:
http://forum.pdfsharp.net/viewtopic.php?p=9591#p9591
internal PdfPage(PdfDictionary dict)内部无所事事。我建议下载源包,引用解决方案中的C#项目,并对代码进行更改。

交换矩形的宽度和高度时,请确保在RotateAtTransform的调用中更新旋转的中心。

答案 1 :(得分:0)

更改

sf.LineAlignment = XLineAlignment.Far;

sf.LineAlignment = XLineAlignment.Center;

您的文本现在在页面中心垂直。然后,您可以使用

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

将文本移到侧面。

相关问题