PDFsharp:有没有办法在页面标题中生成“Y页面X”?

看起来很简单,但我在API中找不到类似getPageCount()的东西。 我可以让它返回当前页面,但不是总页数。 也许我想念它?

我想以某种方式能够在每页的顶部打印“第1页,共9页”,其中“1”当然是当前的页码。

使用PDFsharp,这取决于您。

我假设您正在使用MigraDoc:使用MigraDoc,您可以添加页眉。 为当前页码添加paragraph.AddPageField() ,为总页数添加paragraph.AddPageField()

使用AddPageField的示例

示例中的代码段:

 // Create a paragraph with centered page number. See definition of style "Footer". Paragraph paragraph = new Paragraph(); paragraph.AddTab(); paragraph.AddPageField(); // Add paragraph to footer for odd pages. section.Footers.Primary.Add(paragraph); // Add clone of paragraph to footer for odd pages. Cloning is necessary because an object must // not belong to more than one other object. If you forget cloning an exception is thrown. section.Footers.EvenPage.Add(paragraph.Clone()); 

设置制表位的代码片段(假设DIN A 4的主体为16 cm):

 style = document.Styles[StyleNames.Footer]; style.ParagraphFormat.AddTabStop("8cm", TabAlignment.Center); 

这两个片段都来自链接网站。 示例代码也可供下载。

确保包含using MigraDoc.DocumentObjectModel; 你class上的陈述。

 Document document = new Document(); Section section = document.AddSection(); Paragraph paragraph = new Paragraph(); paragraph.AddText("Page "); paragraph.AddPageField(); paragraph.AddText(" of "); paragraph.AddNumPagesField(); section.Headers.Primary.Add(paragraph); 

我知道这个问题已经过时并且有一个可接受的答案,但是在搜索PDFsharp解决方案时,问题出现在第一个问题中。

为了记录,在PDFsharp中实现这一点很容易。 在PdfSharp.Pdf命名空间下找到的PdfDocument类包含一组页面( PdfDocument.Pages )。 您所要做的就是遍历集合并使用XGraphics对象在每个页面的某处添加页面计数器,您可以使用XGraphics.FromPdfPage(PdfPage)进行实例化。

 using PdfSharp.Pdf; // PdfDocument, PdfPage using PdfSharp.Drawing; // XGraphics, XFont, XBrush, XRect // XStringFormats // Create a new PdfDocument. PdfDocument document = new PdfDocument(); // Add five pages to the document. for(int i = 0; i < 5; ++i) document.AddPage(); // Make a font and a brush to draw the page counter. XFont font = new XFont("Verdana", 8); XBrush brush = XBrushes.Black; // Add the page counter. string noPages = document.Pages.Count.ToString(); for(int i = 0; i < document.Pages.Count; ++i) { PdfPage page = document.Pages[i]; // Make a layout rectangle. XRect layoutRectangle = new XRect(0/*X*/, page.Height-font.Height/*Y*/, page.Width/*Width*/, font.Height/*Height*/); using (XGraphics gfx = XGraphics.FromPdfPage(page)) { gfx.DrawString( "Page " + (i+1).ToString() + " of " + noPages, font, brush, layoutRectangle, XStringFormats.Center); } } 

值得注意的是,如果给定页面已存在XGraphics对象,则在创建新对象之前,需要处理旧对象。 这会失败:

 PdfDocument document = new PdfDocument(); PdfPage page = document.AddPage(); XGraphics gfx1 = XGraphics.FromPage(page); XGraphics gfx2 = XGraphics.FromPage(page);