保持简单:使用制表位
执行此操作的最佳方法与您在大多数文字处理工具中所做的相同:右对齐制表位,放置在页面的右边距,“左”文本居中对齐。这很简单,但我在任何地方都找不到“完整”的解决方案,所以这就是您需要的:
// Grab the current section, and other settings
var section = documentWrapper.CurrentSection;
var footer = section.Footers.Primary;
var reportMeta = documentWrapper.AdminReport.ReportMeta;
// Format, then add the report date to the footer
var footerDate = string.Format("{0:MM/dd/yyyy}", reportMeta.ReportDate);
var footerP = footer.AddParagraph(footerDate);
// Add "Page X of Y" on the next tab stop.
footerP.AddTab();
footerP.AddText("Page ");
footerP.AddPageField();
footerP.AddText(" of ");
footerP.AddNumPagesField();
// The tab stop will need to be on the right edge of the page, just inside the margin
// We need to figure out where that is
var tabStopPosition =
documentWrapper.CurrentPageWidth
- section.PageSetup.LeftMargin
- section.PageSetup.RightMargin;
// Clear all existing tab stops, and add our calculated tab stop, on the right
footerP.Format.TabStops.ClearAll();
footerP.Format.TabStops.AddTabStop(tabStopPosition, TabAlignment.Right);
其中最困难的部分是确定您的制表位应该是什么位置。因为我很无聊而且很喜欢封装,所以我根据页面宽度动态计算制表位位置,减去水平页边距。然而,获取当前页面宽度并不像我想象的那么容易,因为我使用PageFormat 来设置页面尺寸。
下一个挑战:动态获取页面宽度
我真的很讨厌紧密耦合的代码(想想:扇入和扇出),所以即使我现在知道我的页面宽度是多少,甚至到了对其进行硬编码,我仍然希望仅在一个地方对其进行硬编码,然后在其他任何地方引用该地方。
我保留了一个自定义的“has-a”/包装类来将这些东西封装到;这是我的代码中的documentWrapper。此外,我不会将任何 PDFSharp/MigraDoc 类型暴露给我的应用程序的其余部分,因此我使用 ReportMeta 作为通信设置的一种方式。
现在是一些代码。当我设置部分时,我使用 MigraDoc PageFormat 来定义当前部分的页面大小:
// The tab stop will need to be on the right edge of the page, just inside the margin
// We need to figure out where that is
var tabStopPosition =
documentWrapper.CurrentPageWidth
- section.PageSetup.LeftMargin
- section.PageSetup.RightMargin;
// Clear all existing tab stops, and add our calculated tab stop, on the right
footerP.Format.TabStops.ClearAll();
footerP.Format.TabStops.AddTabStop(tabStopPosition / 2, TabAlignment.Center);
footerP.Format.TabStops.AddTabStop(tabStopPosition, TabAlignment.Right);
footerP.Format.Alignment = ParagraphAlignment.Center;
这里真正重要的是,我要存储CurrentPageWidth,这在设置制表位时变得非常重要。 CurrentPageWidth 属性只是 MigraDoc Unit 类型。我可以通过使用 MigraDoc 的 PageSetup.GetPageSize 和我选择的 PageFormat 来确定这是什么。
结果