【问题标题】:PDFsharp Vertical Text on Side of Page页面一侧的 PDFsharp 垂直文本
【发布时间】:2017-03-13 20:45:27
【问题描述】:

鉴于任何现有的 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);

【问题讨论】:

    标签: pdf pdfsharp margins


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      改变

      sf.LineAlignment = XLineAlignment.Far;

      sf.LineAlignment = XLineAlignment.Center;

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

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

      将文本移到一边。

      【讨论】:

        猜你喜欢
        • 2015-04-13
        • 1970-01-01
        • 1970-01-01
        • 2018-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-13
        • 1970-01-01
        相关资源
        最近更新 更多