產品比較

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

發佈 2024年4月3日
分享:

介紹

「便攜式文檔格式」或稱 PDF,是由 Adobe 創建的一種文件格式。PDF 在呈現需要對其文字和圖片進行格式化的文件時非常方便。在當今世界,PDF 文件至關重要,並且在所有企業部門中都被用於文件創建和開票。由於市場上現有的多種 PDF 函式庫,創建 PDF 幾乎變得本能化。在為您的項目使用一個 PDF 函式庫之前,選擇適合您的 PDF 函式庫並權衡每個函式庫的優點和特點是至關重要的。

在這篇文章中,我們將看到如何使用 iTextSharp C# 在 PDF 中添加頁碼。另外,我們還將進行比較。 iTextSharpIronPDF.

如何使用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 的過程,同時管理用戶代理、代理伺服器、Cookie、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。iText7 和 iText.pdfhtml 是必須安裝的軟體包,因為 iText 的功能分佈在許多不同的軟體包中。

如果您選擇使用視覺命令行介面,則需要安裝以下軟體包:

Install-Package iTextSharp

由於iText 7是最新版本,因此我們正在使用它作為我們的解決方案。

使用 IronPDF 添加頁碼

使用 IronPDF 的全面庫可以輕鬆地向 PDF 文件添加頁碼。為了說明,請參閱以下代碼。

using IronPdf;
static void main(string [] args)
{ 
    var renderer = new IronPdf.HtmlToPdf();
    private string header = "<h1>Hello Ironpdf!<h1>";
    PdfDocument pdf = renderer.RenderHtmlAsPdf(header);
    HtmlHeaderFooter htmlFooter = new HtmlHeaderFooter()
    {
        HtmlFragment = "<center><i>{page} of {total-pages}<i></center>"
    };
    // Add footer
    pdf.AddHtmlFooters(htmlFooter);
    pdf.SaveAs("output.pdf");
}
using IronPdf;
static void main(string [] args)
{ 
    var renderer = new IronPdf.HtmlToPdf();
    private string header = "<h1>Hello Ironpdf!<h1>";
    PdfDocument pdf = renderer.RenderHtmlAsPdf(header);
    HtmlHeaderFooter htmlFooter = new HtmlHeaderFooter()
    {
        HtmlFragment = "<center><i>{page} of {total-pages}<i></center>"
    };
    // Add footer
    pdf.AddHtmlFooters(htmlFooter);
    pdf.SaveAs("output.pdf");
}
Imports IronPdf
Shared Sub main(ByVal args() As String)
	Dim renderer = New IronPdf.HtmlToPdf()
	private String header = "<h1>Hello Ironpdf!<h1>"
	Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(header)
	Dim htmlFooter As New HtmlHeaderFooter() With {.HtmlFragment = "<center><i>{page} of {total-pages}<i></center>"}
	' Add footer
	pdf.AddHtmlFooters(htmlFooter)
	pdf.SaveAs("output.pdf")
End Sub
VB   C#

首先,我們定義要轉換成 PDF 的 HTML 文字。此 HTML 內容可以是一個 HTML 段落,也可以是一整個 HTML 頁面。接下來,我們創建一個 HTMLToPdf 類的實例,該類提供將 HTML 轉換為 PDF 的功能 RenderHtmlAsPdf

將 HTML 內容作為參數傳遞給 RenderHtmlAsPdf 功能。我們指定需要轉換為 PDF 的 HTML 內容。頁碼用作佔位符,或是_。{頁面} 的 {總頁數}_** __在這段HTML文本的頁尾部分。

所產生的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(document, new FileStream("output.pdf", FileMode.Create));
            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);
            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);
            table.WriteSelectedRows(0, -1, 150, 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(document, new FileStream("output.pdf", FileMode.Create));
            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);
            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);
            table.WriteSelectedRows(0, -1, 150, 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(document, New FileStream("output.pdf", FileMode.Create))
			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)
			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)
			table.WriteSelectedRows(0, -1, 150, 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
VB   C#

首先,我們正在創建 DocumentPdfWriter 的新對象,這允許我們創建一個空的 PDF 文件。您可以在 PDF 文件中包含文字、照片、表格和其他類型的材料。讓我們使用新段落來添加一些示例文字以進行展示。現在重要的一步是向 PDF 文件添加頁碼。我們將使用 iTextSharp 的頁面事件來完成這個過程。為了能夠在 PDF 生成過程中特定事件發生時覆蓋方法,讓我們首先建立一個從 PdfPageEventHelper 類繼承的類。

在此類中覆蓋 OnEndPage 函數,以添加包含當前頁碼的單個單元格的表格。最後,在關閉文檔之前,我們需要將 PageNumberEventHandler 類的實例連接到 PdfWriter 對象。通過這種配置,每次新頁面添加到 PDF 文件時,PageNumberEventHandler 類的 OnEndPage 函數都會被調用,並在每頁的底部添加頁碼。我們還可以使用現有的 PDF 文件來添加頁碼。

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

結論

總而言之, IronPDF專業性、實用性和與 .NET 環境的無縫整合使其成為需要 HTML 轉 PDF 和相關功能的場景中的最佳選擇,儘管 iTextSharp 仍然是 C# PDF 操作庫領域中的強大競爭者。使用 IronPDF,您可以輕鬆有效地從 HTML 內容創建發票、報告和動態生成的文件,這些都具備現代開發環境中所需的靈活性和適應性。

IronPDF 的 $749 Lite 版本包含永久許可、升級選項和一年的軟體維護。帶有水印的試用期允許用戶在實際環境中評估產品。訪問許可權 頁面. 前往此处 網站 了解有關 Iron Software 的更多資訊。

< 上一頁
C# 報告工具(功能比較)
下一個 >
如何使用iTextSharp在C#中閱讀PDF文件:

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >