如何使用C#代码在 PDF 文档添加页码

向 PDF 文档添加页码不仅实用,而且具有美观效果,因为它能使文档呈现出类似专业出版物的精致外观。无论您处理的是小说的电子版、报告,还是其他类型的长篇文档,添加页码都能显著提高其可读性和使用价值。在本文中,您将学习如何在 C# 中使用 Spire.PDF for .NET 向 PDF 文档添加页码。

安装 Spire.PDF for .NET

首先,您需要将 Spire.PDF for .NET 包中包含的 DLL 文件添加为 .NET 项目的引用。这些 DLL 文件可以通过此链接下载,或者通过 NuGet 进行安装。

cs 复制代码
PM> Install-Package Spire.PDF

PDF 坐标系统

在使用 Spire.PDF for .NET 操作现有 PDF 文档时,需要注意坐标系统的原点位于页面的左上角。x 轴向右延伸,y 轴向下延伸。

通常,页码会放置在文档的页眉或页脚区域。因此,在确定页码的合适位置时,必须考虑页面的尺寸和边距。

在 C# 中在页脚添加左对齐的页码

在 Spire.PDF for .NET 库中,有两个可用的类:PdfPageNumberFieldPdfPageCountField。将它们添加到 PDF 文档的页面时,可以获取并显示当前页码以及总页数。如果您希望插入类似 "第 X 页" 或 "第 X 页,共 Y 页" 的文本,可以使用 PdfCompositeField 类,它允许您将所需文本与一个或多个字段组合成单一字段。

具体示例代码如下:

cs 复制代码
using Spire.Pdf.AutomaticFields;
using Spire.Pdf.Graphics;
using Spire.Pdf;
using System.Drawing;
using Spire.Pdf.License;

namespace AddPageNumbersToLeftCorner
{
    class Program
    {
        static void Main(string[] args)
        {
            // 应用许可证密钥
            LicenseProvider.SetLicenseKey("License Key");

            // 创建 PdfDocument 对象
            PdfDocument doc = new PdfDocument();

            // 加载 PDF 文件
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf");

            // 创建字体、画刷和画笔,用于设置页码的显示样式
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 12, FontStyle.Regular), true);
            PdfBrush brush = PdfBrushes.Black;
            PdfPen pen = new PdfPen(brush, 1.0f);

            // 创建 PdfPageNumberField 对象和 PdfPageCountField 对象
            PdfPageNumberField pageNumberField = new PdfPageNumberField();
            PdfPageCountField pageCountField = new PdfPageCountField();

            // 创建 PdfCompositeField 对象,将页码字段和总页数字段组合为一个字段
            PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField);

            // 获取页面尺寸
            SizeF pageSize = doc.Pages[0].Size;

            // 设置复合字段的位置
            compositeField.Location = new PointF(72, pageSize.Height - 45);

            // 遍历文档中的每一页
            for (int i = 0; i < doc.Pages.Count; i++)
            {

                // 获取指定页面
                PdfPageBase page = doc.Pages[i];

                // 在指定位置绘制一条直线
                page.Canvas.DrawLine(pen, 72, pageSize.Height - 50, pageSize.Width - 72, pageSize.Height - 50);

                // 在页面上绘制复合字段
                compositeField.Draw(page.Canvas);
            }

            // 保存为新的 PDF 文件
            doc.SaveToFile("AddPageNumbersToLeftCorner.pdf");

            // 释放资源
            doc.Dispose();
        }
    }
}

在 C# 中在页脚添加居中对齐的页码

为了将页脚中的页码居中对齐,关键在于动态计算文本 "第 X 页,共 Y 页" 的宽度。这一步计算非常重要,因为它决定了页码(PdfCompositeField)的 X 坐标。为了实现居中对齐,X 坐标的计算方法为:用页面宽度减去页码宽度,然后将结果除以 2,即 (PageWidth - PageNumberWidth) / 2

具体示例代码如下:

cs 复制代码
using Spire.Pdf.AutomaticFields;
using Spire.Pdf.Graphics;
using Spire.Pdf;
using System.Drawing;
using Spire.Pdf.License;

namespace AddPageNumbersToCenter
{
    class Program
    {
        static void Main(string[] args)
        {
            // 应用许可证密钥
            LicenseProvider.SetLicenseKey("License Key");

            // 创建 PdfDocument 对象
            PdfDocument doc = new PdfDocument();

            // 加载 PDF 文件
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf");

            // 创建字体、画刷和画笔,用于设置页码的显示样式
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 12, FontStyle.Regular), true);
            PdfBrush brush = PdfBrushes.Black;
            PdfPen pen = new PdfPen(brush, 1.0f);

            // 创建 PdfPageNumberField 对象和 PdfPageCountField 对象
            PdfPageNumberField pageNumberField = new PdfPageNumberField();
            PdfPageCountField pageCountField = new PdfPageCountField();

            // 创建 PdfCompositeField 对象,将页码字段和总页数字段组合为一个字段
            PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField);


            // 遍历文档中的每一页
            for (int i = 0; i < doc.Pages.Count; i++)
            {

                // 获取指定页面
                PdfPageBase page = doc.Pages[i];

                // 获取页面尺寸
                SizeF pageSize = doc.Pages[i].Size;

                // 在指定位置绘制一条直线
                page.Canvas.DrawLine(pen, 72, pageSize.Height - 50, pageSize.Width - 72, pageSize.Height - 50);

                // 测量 "Page X of Y" 文本的尺寸
                SizeF pageNumberSize = font.MeasureString(string.Format("Page {0} of {1}", i + 1, doc.Pages.Count));

                // 设置复合字段的位置,实现居中对齐
                compositeField.Location = new PointF((pageSize.Width - pageNumberSize.Width) / 2, pageSize.Height - 45);

                // 在页面上绘制复合字段
                compositeField.Draw(page.Canvas);

            }

            // 保存为新的 PDF 文件
            doc.SaveToFile("AddPageNumbersToCenter.pdf");

            // 释放资源
            doc.Dispose();
        }
    }
}

在 C# 中在页脚添加右对齐的页码

为了将页脚中的页码放置在右侧角落,同样需要动态计算文本 "第 X 页,共 Y 页" 的宽度。因为页码(PdfCompositeField)的 X 坐标是通过用页面宽度减去页码宽度与右侧页边距的和来确定的,计算公式如下:

cs 复制代码
PageWidth - (PageNumberWidth + RightPageMargin)

具体示例代码如下:

cs 复制代码
using Spire.Pdf.AutomaticFields;
using Spire.Pdf.Graphics;
using Spire.Pdf;
using System.Drawing;
using Spire.Pdf.License;

namespace AddPageNumbersToRigthCorner
{
    class Program
    {
        static void Main(string[] args)
        {
            // 应用许可证密钥
            LicenseProvider.SetLicenseKey("License Key");

            // 创建 PdfDocument 对象
            PdfDocument doc = new PdfDocument();

            // 加载 PDF 文件
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf");

            // 创建字体、画刷和画笔,用于设置页码的显示样式
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 12, FontStyle.Regular), true);
            PdfBrush brush = PdfBrushes.Black;
            PdfPen pen = new PdfPen(brush, 1.0f);

            // 创建 PdfPageNumberField 对象和 PdfPageCountField 对象
            PdfPageNumberField pageNumberField = new PdfPageNumberField();
            PdfPageCountField pageCountField = new PdfPageCountField();

            // 创建 PdfCompositeField 对象,将页码字段和总页数字段组合为一个字段
            PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField);


            // 遍历文档中的每一页
            for (int i = 0; i < doc.Pages.Count; i++)
            {

                // 获取指定页面
                PdfPageBase page = doc.Pages[i];

                // 获取页面尺寸
                SizeF pageSize = doc.Pages[i].Size;

                // 在指定位置绘制一条直线
                page.Canvas.DrawLine(pen, 72, pageSize.Height - 50, pageSize.Width - 72, pageSize.Height - 50);

                // 测量 "Page X of Y" 文本的尺寸
                SizeF pageNumberSize = font.MeasureString(string.Format("Page {0} of {1}", i + 1, doc.Pages.Count));

                // 设置复合字段的位置,实现右对齐
                compositeField.Location = new PointF(pageSize.Width - pageNumberSize.Width - 72, pageSize.Height - 45);

                // 在页面上绘制复合字段
                compositeField.Draw(page.Canvas);

            }

            // 保存为新的 PDF 文件
            doc.SaveToFile("AddPageNumbersToRigthCorner.pdf");

            // 释放资源
            doc.Dispose();
        }
    }
}
相关推荐
Muyuan199812 小时前
27.RAG 系统中的上下文充分性判断:从 Chunk 数量、FAISS 距离到 LLM Relevance Gate
python·django·pdf·fastapi·faiss
开开心心就好17 小时前
近200个工具的电脑故障修复合集
安全·智能手机·pdf·电脑·consul·memcache·1024程序员节
其实秋天的枫18 小时前
2026年初中英语大纲词汇表1600词
经验分享·pdf
开开心心_Every19 小时前
轻量级PDF阅读器,仅几M大小打开秒开
linux·运维·服务器·安全·macos·pdf·phpstorm
福大大架构师每日一题20 小时前
ragflow v0.25.1 最新版发布:API 统一、PDF 解析性能大幅优化、连接器删除同步全面增强,更新要点一次看懂
pdf·ragflow
cosinmz2 天前
图片太多太乱怎么整理?分享一个我最近常用的图片转 PDF方法
经验分享·小程序·pdf
其实秋天的枫2 天前
2026年新高考英语大纲词汇表3500个电子版PDF(含正序版、乱序版和默写版)
经验分享·pdf
lijfrank2 天前
MacOS 下 VS Code + LaTeX + Skim 双向同步配置
vscode·macos·pdf·latex·mactex
程序员的记录2 天前
AI 实战 - 文档处理(pdf/work/md/txt...)
pdf
Muyuan19983 天前
22.让 RAG Agent 更像真实产品:聊天页面优化、PDF 上传、知识库重建与检索片段展示
python·django·pdf·fastapi