如何使用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();
        }
    }
}
相关推荐
雨田哥19 小时前
Qt Ironclad Reader (授权/加密/OFD签章/OFD验章/PDF/导出)
pdf·ofd·签章·验章·qt ofd·qt pdf·授权加密
狠学嵌入式21 小时前
耗时一个月整理了3款实用免费PDF处理网站
pdf·pdf转word·pdf添加水印·pdf处理·免费工具·免费网站·清页pdf
2501_930707783 天前
使用C#代码替换 PDF 文档中的文本
pdf
周末也要写八哥3 天前
Visual C++6.0下载安装流程及PDF学习手册资源
c++·学习·pdf
优化控制仿真模型3 天前
2026初中英语考纲词汇表(1600词)PDF电子版
经验分享·pdf
2401_876964133 天前
27考研优路|肖睿|唐辛|师大集训营|大牙|B站橙啦101公共课PDF
考研·pdf
2401_876964133 天前
27余峰|苏一|大李子|鹿吖101公共课托管班网课PDF
pdf
SEO-狼术3 天前
Visualize Trends with Bar Charts
pdf·.net
私人珍藏库3 天前
【PC】[吾爱大神原创工具] PDFImageViewer V1 永久免费的PDF图像查看和导出工具
windows·pdf·工具·软件·多功能
小饕3 天前
RAG 数据加载全攻略:从文本到 PDF 的 Loader 选型指南
人工智能·pdf