如何在.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:
1. Directly Set Footer Text with Page Variables
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).
2. Use a Custom HTML Footer
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
pagesCountsetting 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, usefile://(two slashes). - Adjust footer margins (
footer.margin.bottom) to ensure the footer doesn't overlap with your main content.
内容的提问来源于stack exchange,提问作者Kaushik Thanki

