使用 C# 为 PDF 文档添加页码

发布: (2025年12月11日 GMT+8 17:47)
5 min read
原文: Dev.to

Source: Dev.to

Introduction

PDF 文档是信息交换和存储的通用格式,在日常办公任务和技术文档中必不可少。手动为大量 PDF 添加页码既繁琐又耗时。使用 C# 并结合第三方库 Spire.PDF for .NET 自动化此过程,可快速、专业地在每页底部添加 “Page X of Y” 格式的页码。

Installing Spire.PDF for .NET

Spire.PDF for .NET 是一款专业的 .NET PDF 组件,开发者可以无需 Adobe Acrobat 就实现 PDF 的创建、读取、编辑、转换和打印。

NuGet Package Manager Console

Install-Package Spire.PDF

NuGet Package Manager UI

  1. 在 Visual Studio 中右键单击你的项目。
  2. 选择 Manage NuGet Packages…
  3. Browse 选项卡搜索 Spire.PDF
  4. 点击 Install

安装完成后,Spire.PDF 的引用会自动添加,你即可开始使用其 API。

Adding Centered “Page X of Y” Numbers

以下步骤概述了如何加载 PDF、创建复合字段用于页码、将其定位在每页底部居中位置,并保存修改后的文档。

1. Load the Document

使用 PdfDocument 打开目标 PDF。

2. Get Total Page Count

获取 doc.Pages.Count 以构建 “of Y” 部分的字符串。

3. Iterate Through Pages

遍历每一页,计算绘制位置并渲染页码。

4. Save the Document

将结果写入新的 PDF 文件。

Complete Example (C#)

using Spire.Pdf;
using Spire.Pdf.AutomaticFields;
using Spire.Pdf.Graphics;
using System.Drawing;
using Spire.Pdf.License;

namespace AddPageNumbersToCenter
{
    class Program
    {
        static void Main(string[] args)
        {
            // Apply your license key
            LicenseProvider.SetLicenseKey("License Key");

            // Load the PDF file
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Terms of service.pdf");

            // Define appearance of the page number
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 12, FontStyle.Regular), true);
            PdfBrush brush = PdfBrushes.Black;
            PdfPen pen = new PdfPen(brush, 1.0f);

            // Create fields for page number and total page count
            PdfPageNumberField pageNumberField = new PdfPageNumberField();
            PdfPageCountField pageCountField = new PdfPageCountField();

            // Composite field combines the two fields with the desired format
            PdfCompositeField compositeField = new PdfCompositeField(
                font, brush, "Page {0} of {1}", pageNumberField, pageCountField);

            // Add the composite field to each page
            for (int i = 0; i < doc.Pages.Count; i++)
            {
                PdfPageBase page = doc.Pages[i];
                SizeF pageSize = page.Size;

                // Optional: draw a separator line
                page.Canvas.DrawLine(pen, 72, pageSize.Height - 50, pageSize.Width - 72, pageSize.Height - 50);

                // Measure the width of the page number string
                SizeF pageNumberSize = font.MeasureString(
                    string.Format("Page {0} of {1}", i + 1, doc.Pages.Count));

                // Center the composite field at the bottom
                compositeField.Location = new PointF(
                    (pageSize.Width - pageNumberSize.Width) / 2,
                    pageSize.Height - 45);

                // Render the field
                compositeField.Draw(page.Canvas);
            }

            // Save the modified PDF
            doc.SaveToFile("AddPageNumbersToCenter.pdf");
            doc.Dispose();
        }
    }
}

Key Code Explanations

CodeExplanation
doc.LoadFromFile(@"C:\...\Terms of service.pdf");加载源 PDF。
doc.Pages.Count获取总页数。
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 12, FontStyle.Regular), true);创建 12 pt Times New Roman 字体。
PdfBrush brush = PdfBrushes.Black;将文字颜色设为黑色。
PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField);构建 “Page X of Y” 字段。
compositeField.Location = new PointF((pageSize.Width - pageNumberSize.Width) / 2, pageSize.Height - 45);将字段水平居中并放置在底部附近。
compositeField.Draw(page.Canvas);在当前页上绘制字段。
doc.SaveToFile("AddPageNumbersToCenter.pdf");将带页码的新 PDF 保存。

Customizing Page Numbers

Spire.PDF for .NET 提供了丰富的灵活性:

  • Positioning – 调整 Location 可改变垂直或水平位置。
  • Font Styles & Colors – 使用任意 PdfTrueTypeFontPdfBrush
  • Formats – 更改格式字符串(例如 "Page {0}""第{0}页/共{1}页")。
  • Different Page Sizes – 如循环中所示,针对不同页尺寸重新计算位置。
  • Additional Effects – 可与水印、页眉、页脚或其他自动字段组合使用。

Conclusion

通过本教程,你可以使用 C# 和 Spire.PDF for .NET 自动为 PDF 文档添加 “Page X of Y” 页码。这消除了手动、易出错的操作,提升了 PDF 的专业性和可读性。进一步探索该库的其他功能——如水印、批注和格式转换——以进一步增强文档处理应用。

Back to Blog

相关文章

阅读更多 »