ahs*_*ant 1 c# pdf-generation pdfsharp migradoc
我知道如何显示页码以及如何在页脚中对齐它们。但是我的问题是我的页脚包含一些自定义文本,这些文本应该左对齐,页码应该与右角对齐。
string footer = "My custom footer";
Paragraph footerParagraph = section.Footers.Primary.AddParagraph(footer);
footerParagraph.AddTab();
footerParagraph.AddPageField();
Run Code Online (Sandbox Code Playgroud)
上面将为第 1 页生成“我的自定义页脚 1”,我需要页面 nmuber 位于页面的最右上角。我可以添加额外的空格或制表符,但我认为必须有一种干净的方法来实现这一点。谢谢。
小智 5
执行此操作的最佳方法与在大多数文字处理工具中执行的操作相同:使用右对齐制表位,将其放置在页面的右边距。这非常简单,但我在任何地方都找不到“完整”的解决方案,所以这就是您需要的:
// 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);
Run Code Online (Sandbox Code Playgroud)
其中最难的部分是弄清楚制表位的位置应该是什么。因为我很无聊并且非常喜欢封装,所以我根据页面宽度动态计算制表位位置,减去水平页边距。然而,获取当前页面宽度并不像我想象的那么容易,因为我正在用来PageFormat设置页面尺寸。
首先,我真的很讨厌紧密耦合的代码(想想:扇入和扇出),所以即使我此时知道我的页面宽度是多少,甚至到了对其进行硬编码的程度,我仍然想要仅将其硬编码在一个位置,然后在其他地方引用该位置。
我保留一个自定义的“has-a”/包装类来将这些东西封装到;这documentWrapper在我的代码中。此外,我不会向应用程序的其余部分公开任何 PDFSharp/MigraDoc 类型,因此我将其用作ReportMeta传达设置的方式。
现在来看一些代码。当我设置该部分时,我使用 MigraDocPageFormat定义当前部分的页面大小:
// Create, and set the new section
var section = documentWrapper.CurrentDocument.AddSection();
documentWrapper.CurrentSection = section;
// Some basic setup
section.PageSetup.PageFormat = PageFormat.Letter; // Here's my little bit of hard-coding
Unit pageWidth, pageHeight;
PageSetup.GetPageSize(PageFormat.Letter, out pageWidth, out pageHeight);
var reportMeta = documentWrapper.AdminReport.ReportMeta;
if (reportMeta.PageOrientation == AdminReportMeta.ORIENT_LANDSCAPE)
{
section.PageSetup.Orientation = Orientation.Landscape;
documentWrapper.CurrentPageWidth = pageHeight;
}
else
{
section.PageSetup.Orientation = Orientation.Portrait;
documentWrapper.CurrentPageWidth = pageWidth;
}
Run Code Online (Sandbox Code Playgroud)
这里真正重要的是,我要存储CurrentPageWidth,这在设置制表位时变得非常重要。该CurrentPageWidth属性只是 MigraDocUnit类型。我可以通过使用 MigraDocPageSetup.GetPageSize和我选择的PageFormat.