You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.NET C# API项目中使用OpenHtmlToPdf(v1.12.0.0)为每一页PDF添加页码?

Absolutely! You can add a footer with page numbers using OpenHtmlToPdf—since this package is a wrapper around wkhtmltopdf, we can leverage wkhtmltopdf's built-in footer configuration options. Here's how to implement it, with two common approaches:

You can use wkhtmltopdf's built-in variables ([page] for current page number, [topage] for total pages) directly in your configuration. Make sure you've enabled pagesCount to access the total page count.

Here's your modified code (note I fixed a typo: Comressed → Compressed):

var pdf = Pdf
    .From(contents)
    .OfSize(PaperSize.A4)
    .WithTitle($"Report Data")
    .WithoutOutline()
    .WithObjectSetting("web.defaultEncoding", "utf-8")
    // Enable page count tracking to use [topage] variable
    .WithObjectSetting("pagesCount", "true")
    // Add centered footer with page numbers
    .WithObjectSetting("footer.center", "Page [page] of [topage]")
    // Optional: Adjust footer styling
    .WithObjectSetting("footer.fontSize", "10")
    .WithObjectSetting("footer.margin.bottom", "10mm")
    .Portrait()
    .Compressed()
    .Content();

You can also use footer.left or footer.right if you want to align content to the sides (e.g., a copyright notice on the left).

For more control over styling (like fonts, colors, or layout), you can reference an external HTML file for the footer.

First, create a simple HTML file for your footer (e.g., footer.html):

<div style="width: 100%; text-align: center; font-family: Arial, sans-serif; font-size: 10px; padding: 5px;">
    Page <span>[page]</span> of <span>[topage]</span>
    <p style="font-size: 8px; margin-top: 2px;">© 2024 Your Company</p>
</div>

Then update your PDF generation code to reference this file:

var pdf = Pdf
    .From(contents)
    .OfSize(PaperSize.A4)
    .WithTitle($"Report Data")
    .WithoutOutline()
    .WithObjectSetting("web.defaultEncoding", "utf-8")
    .WithObjectSetting("pagesCount", "true")
    // Reference your footer HTML file (use file:/// prefix for local paths)
    .WithObjectSetting("footer.htmlUrl", "file:///C:/Projects/YourApp/footer.html")
    // Optional: Adjust footer margin to prevent overlap with content
    .WithObjectSetting("footer.margin.bottom", "15mm")
    .Portrait()
    .Compressed()
    .Content();

Key Notes

  • The pagesCount setting is required to make the [topage] variable work correctly—without it, only the current page number will display.
  • For local file paths on Windows, use the file:/// prefix (three slashes). On Linux/macOS, use file:// (two slashes).
  • Adjust footer margins (footer.margin.bottom) to ensure the footer doesn't overlap with your main content.

内容的提问来源于stack exchange,提问作者Kaushik Thanki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 16:42:30