跳過到頁腳內容
產品比較

如何在C#中使用iTextSharp在PDF中添加頁碼

"可攜式文檔格式",或簡稱PDF,是由Adobe創建的一種文件格式。 當呈現需要保持文本和圖像一致格式的文檔時,PDF非常有用。 在當前的世界中,PDF文件是必不可少的,並且在所有企業部門中用於文檔創建和開票。 由於市場上現有的多個PDF庫,創建PDF幾乎已成為本能。在為您的項目使用PDF庫之前,選擇適合您的PDF庫並權衡每個庫的優勢和特性是至關重要的。

在本文中,我們將看到如何使用iTextSharp C#在PDF中添加頁碼。 Also, we are going to 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包管理器,您可以在工具下找到Visual命令行界面。 下面的命令應該輸入到包管理終端選項卡中。

Install-Package IronPdf

或者我們可以使用包管理器方法。 可以使用Visual Studio的NuGet包管理器選項將包直接安裝到解決方案中。 在NuGet網站上有一個搜索框可用於定位包。我們只需在包管理器中查找"IronPDF",如下圖所示:

如何使用iTextSharp在C#中為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。 需要安裝iText7和iText.pdfhtml,因為iText功能分布在許多包中。

如果您選擇Visual命令行界面,則需要安裝以下包:

Install-Package iText7
Install-Package itext7.pdfhtml
Install-Package iText7
Install-Package itext7.pdfhtml
SHELL

由於iText 7是最新版本,我們在解決方案中使用的是該版本。

使用IronPDF添加頁碼

通過IronPDF的完整庫,向PDF文件中添加頁碼變得簡單。 例如,請參見下面的代碼:

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        // Initialize the IronPdf renderer
        var renderer = new IronPdf.HtmlToPdf();

        // HTML content to convert to PDF
        string header = "<h1>Hello Ironpdf!</h1>";

        // Render the HTML content to PDF
        PdfDocument pdf = renderer.RenderHtmlAsPdf(header);

        // Define the footer with page number placeholders
        HtmlHeaderFooter htmlFooter = new HtmlHeaderFooter
        {
            HtmlFragment = "<center><i>{page} of {total-pages}</i></center>"
        };

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

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

class Program
{
    static void Main(string[] args)
    {
        // Initialize the IronPdf renderer
        var renderer = new IronPdf.HtmlToPdf();

        // HTML content to convert to PDF
        string header = "<h1>Hello Ironpdf!</h1>";

        // Render the HTML content to PDF
        PdfDocument pdf = renderer.RenderHtmlAsPdf(header);

        // Define the footer with page number placeholders
        HtmlHeaderFooter htmlFooter = new HtmlHeaderFooter
        {
            HtmlFragment = "<center><i>{page} of {total-pages}</i></center>"
        };

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

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

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Initialize the IronPdf renderer
		Dim renderer = New IronPdf.HtmlToPdf()

		' HTML content to convert to PDF
		Dim header As String = "<h1>Hello Ironpdf!</h1>"

		' Render the HTML content to PDF
		Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(header)

		' Define the footer with page number placeholders
		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 output PDF file
		pdf.SaveAs("output.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

解釋

  1. 初始化渲染器: 我們創建一個HtmlToPdf的實例,提供HTML到PDF的轉換功能。
  2. 定義HTML內容: 需要轉換為PDF的HTML內容已被指定。
  3. 渲染HTML內容: 使用RenderHtmlAsPdf函數將HTML轉換為PDF文檔。
  4. 定義頁腳: 頁碼以占位符的形式出現在HTML頁腳文本中。
  5. 添加頁腳並保存PDF: 將頁腳應用到文檔並存儲為PDF文件。

如何在iTextSharp中使用C#添加頁碼到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 document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("output.pdf", FileMode.Create));

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

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

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

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

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

            // Add page number to the table cell
            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, 150, document.Bottom, writer.DirectContent);
        }
    }
}
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 document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("output.pdf", FileMode.Create));

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

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

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

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

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

            // Add page number to the table cell
            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, 150, document.Bottom, writer.DirectContent);
        }
    }
}
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 document As New Document()
			Dim writer As PdfWriter = PdfWriter.GetInstance(document, New FileStream("output.pdf", FileMode.Create))

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

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

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

	Public Class PageNumberEventHandler
		Inherits PdfPageEventHelper

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

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

			' Add page number to the table cell
			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, 150, document.Bottom, writer.DirectContent)
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

解釋

  1. 創建PDF文檔: 初始化一個新的DocumentPdfWriter以生成一個空的PDF文件。
  2. 添加內容: 向文檔中添加基本內容,例如段落。
  3. 頁碼: 我們利用iTextSharp的事件處理來包含頁碼。 我們創建一個自定義的類,繼承自PdfPageEventHelper
  4. 覆寫OnEndPage 在自定義類中,覆寫OnEndPage方法以在每個頁面的底部添加頁碼。
  5. 關閉文檔: 通過關閉文檔來完成文檔。

如何在iTextSharp中使用C#添加頁碼到PDF:圖3 - iTextSharp:輸出包含頁碼的PDF

結論

總之,IronPDF的專業化、可用性和與.NET環境的無縫整合使其成為需要HTML到PDF轉換和相關功能的場景中最佳選擇,即使iTextSharp在C# PDF操作庫中仍然是一個強勁的競爭者。 使用IronPDF,您可以從HTML內容中創建發票、報告和動態生成的文檔,具備在現代開發環境中成功所需的輕鬆、有效性和適應性。

鐵PDF的Lite版本包括永久許可升級選項和一年的軟件維護。 帶有水印的試用期允許用戶在實際環境中評估產品。 訪問許可頁面了解更多信息。 欲了解更多關於Iron Software的資訊,請訪問他們的網站

請注意iTextSharp 是其各自所有者的註冊商標。 本網站未被 iTextSharp 授權、贊助或認可。所有產品名稱、商標和品牌均為其各自所有者的財產。 比較僅供信息參考,並反映撰寫時公開可用的信息。

常見問題解答

如何使用 C# 中的 iTextSharp 為 PDF 新增頁碼?

要在 C# 中使用 iTextSharp 新增頁碼,您可以建立一個繼承自PdfPageEventHelper自訂類別。重寫OnEndPage方法來插入頁碼,並將此事件附加到PdfWriter實例。

為什麼PDF文件在各個領域都至關重要?

PDF文件能夠保持文字和圖像格式的一致性,這對於企業各部門的文件建立和發票處理至關重要。它們能夠可靠地以專業的方式呈現文件。

使用 IronPDF 進行 PDF 處理有哪些優勢?

IronPDF 提供強大的功能,可在 .NET 環境下建立、檢視和編輯 PDF 檔案。它擅長將 HTML、JavaScript 和圖像轉換為 PDF,並支援自訂頁首、頁尾和浮水印。

IronPDF 能否處理支援 JavaScript 的 HTML 轉 PDF 轉換?

是的,IronPDF 可以將 HTML 內容(包括 JavaScript)轉換為 PDF,同時保持其在 Web 瀏覽器中的佈局和功能。

如何在 C# 專案中安裝 IronPDF?

您可以使用 Visual Studio 中的 NuGet 套件管理器安裝 IronPDF。只需搜尋“IronPDF”並將其添加到您的專案中即可開始使用其功能。

IronPDF提供的試用期有何意義?

IronPDF 的試用期讓開發人員可以透過浮水印的試用版在實際應用中探索其功能和功能,幫助他們在購買授權之前評估其適用性。

iTextSharp 在新增頁碼方面與 IronPDF 相比如何?

雖然 iTextSharp 使用事件處理來新增頁碼,但 IronPDF 提供了一種更直接的方法,使用 HTML 範本來建立頁首和頁腳,使其成為尋求易用性的 .NET 開發人員的理想選擇。

為 C# 專案選擇 PDF 庫時應考慮哪些因素?

考慮一下各個庫提供的功能。例如,IronPDF 專注於 HTML 轉 PDF,並且與 .NET 框架整合良好;而 iTextSharp 則提供強大的加密和文字擷取功能。

iTextSharp 是否相容於 .NET 10 以新增頁碼?還是我應該使用 iText 7?

iTextSharp(5.x 版本)已正式棄用並進入維護模式;它只接收安全性修復,不再提供任何新功能更新。它不直接面向 .NET 10,在較新的 .NET 版本中使用它可能會導致相容性問題。對於新項目或升級到 .NET 10 的項目,強烈建議使用 iText 7(或 iText Core),因為它支援最新的框架,並且相比 iTextSharp 進行了改進。 ([itextpdf.com](https://itextpdf.com/products/itextsharp?utm_source=openai))

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。