跳至页脚内容
使用IRONPDF

如何使用C#在PDF中添加页码

“便携式文档格式(PDF)”是一种由Adobe创建的文件格式。 在需要格式化文本和照片时,PDF在展示论文时非常方便。 在当今世界,PDF文件非常重要,并在所有企业领域用于文档创建和开具发票。 由于市场上现有的多个PDF库,创建PDF几乎变得本能。在为您的项目使用PDF库之前,选择合适的PDF库至关重要,您需要权衡每个库的优点和特点。

本文中,我们将看到如何使用iTextSharp C#在PDF中添加页码。 Also, we will compare iTextSharp with IronPDF.

如何使用iTextSharp C#在PDF中添加页码

  1. 使用任何IDE创建一个新的C#项目。
  2. 创建一个新的PDF对象。
  3. 将页码添加到HTML页脚。
  4. 从HTML素材创建PDF。
  5. 将PDF文件保存到您的计算机。

什么是IronPDF

IronPDF是一个强大的PDF .NET框架,开发人员可以轻松地使用它生成、查看和编辑PDF。 IronPDF是一个复杂的工具,内部运行于一个Chromium引擎。 它可以将HTML5、JavaScript、CSS和图片文件转换为PDF,添加自定义页眉和页脚,并生成与浏览器中显示相同的PDF。 IronPDF支持许多在线和网络格式,包括HTML、ASPX、Razor View和MVC。

IronPDF 功能

  • 使用.NET C#代码创建、读取和简单编辑PDF文件。
  • 从网站URL链接创建PDF的过程,同时管理用户代理、代理、Cookies、HTTP头和表单变量,以使用HTML登录表单启用登录。
  • 从现有PDF文件中移除图像。
  • 包括PDF的元素:表格、文本、照片、书签、水印、页眉、页脚等。
  • 能够轻松分离和合并多个PDF文档的页面。

要了解有关IronPDF文档的更多信息,请参考这里

安装 IronPDF。

在Visual Studio工具中,选择NuGet包管理器,您可以在工具下找到可视命令行界面。 应在包管理终端选项卡中输入以下命令。

Install-Package IronPdf

或者我们可以使用包管理器方法。 可以通过Visual Studio的NuGet包管理器选项将包直接安装到解决方案中。 NuGet网站上有一个搜索框可以定位包。我们只需在包管理器中查找“IronPDF”,如下截图所示:

在C#中使用iTextSharp在PDF中添加页码:图1 - 从包管理器安装IronPDF

上面显示了相关搜索结果的列表。 为了在您的系统上安装包,请做出必要的选择。

现在包已下载并安装,可以在当前项目中使用。

什么是iTextSharp

iTextSharp是一个用于在C#中生成和修改PDF文档的灵活库。 它提供了几种功能,如加密、PDF合并、文本和图片提取等等。 iTextSharp是一个高效的工具,可用于许多任务,包括向PDF中添加页码。

iTextSharp功能

  • iText库提供了一个用于生成PDF文档的API。
  • iText程序可将HTML和XML字符串解析为PDF文件。
  • 我们可以使用iText库为PDF文档添加书签、页码和标记。
  • 我们还可以使用iText库将一个PDF文档拆分为多个PDF,或将多个PDF文档合并为一个PDF。
  • 我们可以使用iText修改PDF表单。

安装iTextSharp

使用NuGet包管理器查找iText。 由于iText功能分布在多个包中,需要安装iText7和iText.pdfhtml。

如果选择Visual命令行界面,需要安装以下包:

Install-Package iTextSharp

由于iText 7是最新版本,因此我们在解决方案中使用它。

使用IronPDF添加页码

通过IronPDF的全面库,向PDF文件中添加页码变得很简单。 为了说明,请参见下面的代码。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        // Create a new HtmlToPdf renderer instance
        var renderer = new HtmlToPdf();

        // Define the HTML content with a header
        string header = "<h1>Hello IronPDF!</h1>";

        // Render the HTML as a PDF document
        PdfDocument pdf = renderer.RenderHtmlAsPdf(header);

        // Define the HTML footer with page numbers
        HtmlHeaderFooter htmlFooter = new HtmlHeaderFooter()
        {
            HtmlFragment = "<center><i>{page} of {total-pages}</i></center>"
        };

        // Add footer to the PDF
        pdf.AddHtmlFooters(htmlFooter);

        // Save the PDF document to a file
        pdf.SaveAs("output.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        // Create a new HtmlToPdf renderer instance
        var renderer = new HtmlToPdf();

        // Define the HTML content with a header
        string header = "<h1>Hello IronPDF!</h1>";

        // Render the HTML as a PDF document
        PdfDocument pdf = renderer.RenderHtmlAsPdf(header);

        // Define the HTML footer with page numbers
        HtmlHeaderFooter htmlFooter = new HtmlHeaderFooter()
        {
            HtmlFragment = "<center><i>{page} of {total-pages}</i></center>"
        };

        // Add footer to the PDF
        pdf.AddHtmlFooters(htmlFooter);

        // Save the PDF document to a file
        pdf.SaveAs("output.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create a new HtmlToPdf renderer instance
		Dim renderer = New HtmlToPdf()

		' Define the HTML content with a header
		Dim header As String = "<h1>Hello IronPDF!</h1>"

		' Render the HTML as a PDF document
		Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(header)

		' Define the HTML footer with page numbers
		Dim htmlFooter As New HtmlHeaderFooter() With {.HtmlFragment = "<center><i>{page} of {total-pages}</i></center>"}

		' Add footer to the PDF
		pdf.AddHtmlFooters(htmlFooter)

		' Save the PDF document to a file
		pdf.SaveAs("output.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

首先,我们定义需要转换为PDF的HTML文本。 此HTML内容可以由单个HTML段落或整页HTML组成。 接下来,我们创建一个HtmlToPdf类的实例,该类提供HTML到PDF的转换功能RenderHtmlAsPdf

将HTML内容作为参数传递给RenderHtmlAsPdf函数。 我们指定需要转换为PDF的HTML材料。 页码在此HTML文本的页脚部分中表示为占位符,或{page} of {total-pages}

此方法返回创建的PDF文档,作为一个PdfDocument对象。 使用SaveAs方法,我们将PDF文档保存为名为"output.pdf"的文件。 或者,我们可以使用OpenInDefaultPDFViewer功能,通过系统的默认PDF阅读器打开创建的PDF文档。 我们还可以使用上述方法为现有的PDF文件添加页码。

如何在C#中使用iTextSharp在PDF中添加页码:图2 - IronPDF:输出的PDF带有页码

要了解有关IronPDF代码的更多信息,请参考这里

使用iTextSharp添加页码

首先,让我们使用iTextSharp生成一个新的PDF文档。 这是一个如何使用页码创建新PDF文档的基本示例:

using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a new PDF document
            Document doc = new Document();
            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("output.pdf", FileMode.Create));

            // Open the document to add content
            doc.Open();
            doc.Add(new Paragraph("Hello, world!"));

            // Attach page number event to PDF writer
            writer.PageEvent = new PageNumberEventHandler();

            // Close the document
            doc.Close();
        }
    }

    public class PageNumberEventHandler : PdfPageEventHelper
    {
        public override void OnOpenDocument(PdfWriter writer, Document document)
        {
            base.OnOpenDocument(writer, document);
        }

        public override void OnEndPage(PdfWriter writer, Document document)
        {
            base.OnEndPage(writer, document);

            // Create a table to hold the page number
            PdfPTable table = new PdfPTable(1);
            table.TotalWidth = 300f;
            table.HorizontalAlignment = Element.ALIGN_CENTER;

            PdfPCell cell = new PdfPCell(new Phrase($"Page {writer.PageNumber}"));
            cell.Border = 0;
            table.AddCell(cell);

            // Write the table at the bottom of the page
            table.WriteSelectedRows(0, -1, 150f, document.Bottom, writer.DirectContent);
        }

        public override void OnCloseDocument(PdfWriter writer, Document document)
        {
            base.OnCloseDocument(writer, document);
        }
    }
}
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a new PDF document
            Document doc = new Document();
            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("output.pdf", FileMode.Create));

            // Open the document to add content
            doc.Open();
            doc.Add(new Paragraph("Hello, world!"));

            // Attach page number event to PDF writer
            writer.PageEvent = new PageNumberEventHandler();

            // Close the document
            doc.Close();
        }
    }

    public class PageNumberEventHandler : PdfPageEventHelper
    {
        public override void OnOpenDocument(PdfWriter writer, Document document)
        {
            base.OnOpenDocument(writer, document);
        }

        public override void OnEndPage(PdfWriter writer, Document document)
        {
            base.OnEndPage(writer, document);

            // Create a table to hold the page number
            PdfPTable table = new PdfPTable(1);
            table.TotalWidth = 300f;
            table.HorizontalAlignment = Element.ALIGN_CENTER;

            PdfPCell cell = new PdfPCell(new Phrase($"Page {writer.PageNumber}"));
            cell.Border = 0;
            table.AddCell(cell);

            // Write the table at the bottom of the page
            table.WriteSelectedRows(0, -1, 150f, document.Bottom, writer.DirectContent);
        }

        public override void OnCloseDocument(PdfWriter writer, Document document)
        {
            base.OnCloseDocument(writer, document);
        }
    }
}
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf

Namespace ConsoleApp1
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Create a new PDF document
			Dim doc As New Document()
			Dim writer As PdfWriter = PdfWriter.GetInstance(doc, New FileStream("output.pdf", FileMode.Create))

			' Open the document to add content
			doc.Open()
			doc.Add(New Paragraph("Hello, world!"))

			' Attach page number event to PDF writer
			writer.PageEvent = New PageNumberEventHandler()

			' Close the document
			doc.Close()
		End Sub
	End Class

	Public Class PageNumberEventHandler
		Inherits PdfPageEventHelper

		Public Overrides Sub OnOpenDocument(ByVal writer As PdfWriter, ByVal document As Document)
			MyBase.OnOpenDocument(writer, document)
		End Sub

		Public Overrides Sub OnEndPage(ByVal writer As PdfWriter, ByVal document As Document)
			MyBase.OnEndPage(writer, document)

			' Create a table to hold the page number
			Dim table As New PdfPTable(1)
			table.TotalWidth = 300F
			table.HorizontalAlignment = Element.ALIGN_CENTER

			Dim cell As New PdfPCell(New Phrase($"Page {writer.PageNumber}"))
			cell.Border = 0
			table.AddCell(cell)

			' Write the table at the bottom of the page
			table.WriteSelectedRows(0, -1, 150F, document.Bottom, writer.DirectContent)
		End Sub

		Public Overrides Sub OnCloseDocument(ByVal writer As PdfWriter, ByVal document As Document)
			MyBase.OnCloseDocument(writer, document)
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

首先,我们为DocumentPdfWriter创建一个新对象,这样我们就可以创建一个空的PDF文件。您可以在PDF文档中包含文本、照片、表格和其他类型的材料。 我们用一个Paragraph来添加一些示例文本以作演示。 现在,重要的一步是为PDF文档添加页码。 我们将使用iTextSharp的页面事件来实现这一点。 我们首先定义一个类,该类继承自PdfPageEventHelper类,以便能够覆盖在PDF生成过程中发生特定事件时调用的方法。

在此类中覆盖OnEndPage函数,以添加包含当前页码的单元格的表格。 最后,在关闭文档之前,我们需要将PageNumberEventHandler类的实例连接到PdfWriter对象。 通过这种配置,每次向PDF文档添加新页面时,PageNumberEventHandler类的OnEndPage函数都会被调用,在每页底部添加页码。 我们还可以使用现有的PDF文档来添加页码。

在C#中使用iTextSharp在PDF中添加页码:图3 - iTextSharp:输出PDF中带有页码

结论

总之,尽管iTextSharp在C#PDF操作库中仍然是一位强劲的竞争者,但IronPDF在专业化、可用性以及与.NET环境的无缝集成方面的优势,使其成为需要HTML到PDF转换及相关功能场景中的最佳选择。 使用IronPDF,您可以轻松、有效和灵活地从HTML内容创建发票、报告和动态生成的文档,以在现代开发环境中取得成功。

IronPDF的Lite版本中包含永久授权、升级选项和一年的软件维护。 带水印的试用期允许用户在实际设置中评估产品。 访问许可证页面以获取更多详细信息。 访问此网站以了解更多关于Iron Software的信息。

常见问题解答

如何使用 C# 向 PDF 添加页码?

您可以使用IronPDF通过定义带有页码占位符的HTML内容并使用AddHtmlFooters方法将其应用为PDF的页脚来为PDF添加页码。

使用IronPDF进行PDF操作的好处是什么?

IronPDF提供强大的PDF.NET框架功能,支持HTML5、JavaScript、CSS和图片到PDF的转换,轻松通过自定义页眉和页脚操控PDF。

iTextSharp与IronPDF相比如何用于添加页码?

iTextSharp使用PdfPageEventHelper类来处理页码,而IronPDF提供更简单的方法,让您定义带有页码占位符的HTML页脚。

我可以操控现有PDF文件添加页码吗?

是的,使用IronPDF,您可以通过渲染带有页码占位符的HTML页脚并将其与原始文档合并,为现有PDF文件添加页码。

转换HTML为PDF的首选方法是什么?

由于无缝集成.NET环境和处理HTML5、JavaScript、CSS的能力,IronPDF是HTML到PDF转换的首选工具。

在C#项目中使用IronPDF的安装步骤是什么?

您可以在Visual Studio的NuGet包管理器中搜索‘IronPDF’并将其添加到您的C#项目中来安装IronPDF。

如何确保我的PDF在使用C#时具有准确的页码?

使用IronPDF,通过定义带有页码占位符的HTML模板并在所有PDF页面上一致应用来确保页码准确。

IronPDF 提供哪些许可选项?

IronPDF提供一个带有永久许可证的‘Lite’版,升级选项和一年的软件维护,以及水印试用期用于评估。

在哪里可以找到使用IronPDF的详细示例和文档?

IronPDF的全面文档和示例可以在他们的官方网站ironpdf.com上找到。

IronPDF 是否完全兼容 .NET 10?我可以在 .NET 10 项目中使用页码功能吗?

是的,IronPDF 支持 .NET 10,其所有功能(包括通过页眉或页脚中的占位符进行页码标注)均可在 .NET 10 项目中开箱即用,无需任何特殊配置或变通方法。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。