【发布时间】: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);
【问题讨论】: