它看起來很簡單,但我無法在API中找到類似getPageCount()的東西。我可以得到它返回當前頁面,但不是總頁數。也許我錯過了它?PDFsharp:有沒有辦法在頁面的標題中生成「Y的頁面X」?
我想以某種方式能夠在每頁頂部打印「第1頁,共9頁」,其中'1'當然是當前頁碼。
它看起來很簡單,但我無法在API中找到類似getPageCount()的東西。我可以得到它返回當前頁面,但不是總頁數。也許我錯過了它?PDFsharp:有沒有辦法在頁面的標題中生成「Y的頁面X」?
我想以某種方式能夠在每頁頂部打印「第1頁,共9頁」,其中'1'當然是當前頁碼。
使用PDFsharp取決於您。
我推測你正在使用MigraDoc:使用MigraDoc你可以添加一個頁眉。爲當前頁碼添加paragraph.AddPageField()
,爲總頁數添加paragraph.AddNumPagesField()
。從樣品
代碼段:
// 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釐米):
style = document.Styles[StyleNames.Footer];
style.ParagraphFormat.AddTabStop("8cm", TabAlignment.Center);
這兩個摘錄都來自鏈接的網站。示例代碼也可以下載。
此頁面顯示的示例不適用。我的意思是頁碼不會改變。 –
@Marek Bar:AddNumPagesField添加文檔中的頁面數量(並且不會在頁面之間更改),AddPageField添加當前頁面編號並隨頁面而改變。 –
@PDFsharpTeam ...如果我想只顯示頁碼,如果PDF超過一頁長...我應該怎麼做?現在,我的PDF顯示「Pag:1」,即使我總共有一頁。 – Romias
請確保在您的班級中包含using MigraDoc.DocumentObjectModel;
聲明。
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);
這對我來說完美無瑕。 – ddz
我知道這個問題很老,並且有一個可接受的答案,但是當搜索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);
請問您能展示一些代碼嗎? – sarseyn