跳過到頁腳內容
產品比較
如何使用 ITextSharp 在 C# 中向 PDF 添加數位簽章

使用Itextsharp在C#中向PDF添加數字簽名

Full Comparison

Looking for a detailed feature-by-feature breakdown? See how IronPDF stacks up against Itext on pricing, HTML support, and licensing.

View Full Comparison

在當今瞬息萬變的世界裡,紙本文件正迅速被電子文件所取代。 無論是簽署合約、審批發票或提交政府表格,電子文檔都已成為標準。 然而,這種便利性也帶來了一個新的挑戰:確保數位文件的真實性和完整性。

電子簽名提供了一種解決方案。 數位簽名不僅僅是在觸控螢幕上隨意塗鴉,它還使用加密技術來驗證簽名者的身份,並確保文件內容保持不變。 對於 C# 開發人員來說,將這種等級的安全性整合到 PDF 工作流程中現在比以往任何時候都更容易,尤其是有IronPDFiTextSharp等工具。 在本文中,我們將引導您完成對 PDF 進行數位簽章的過程,比較不同的函式庫,提供最佳實踐,並幫助您為下一個專案選擇合適的解決方案。

瞭解數位簽章

數位簽章是一種加密技術,用於驗證數位訊息或文件的真實性和完整性。 與簡單的圖像簽章或打字姓名不同,數位簽章使用私人金鑰來加密文件的切細值。 然後,任何人都可以使用簽章者的公開金鑰驗證此加密的散列。

為什麼這很重要? 因為它能確保兩件事

1.身份驗證– 此簽章驗證了來自所述寄件者的 PDF 文件。

2.Integrity - 文件自簽署以來未經修改。 即使是微小的改動也會導致簽名無效。

數位簽章在許多司法管轄區都具有法律約束力,在金融、醫療保健、法律和政府等產業中至關重要。

為什麼要在 PDF 中使用數位簽章?

PDF 是分發從法律合約到官方報告等專業文件的標準格式。 將數位簽章加入 PDF 有幾個重要的目的:

-合法性與合規性:數位簽章符合 eIDAS(歐洲)、ESIGN(美國)等法規,因此具有法律認可度。

-安全性:簽名文件不能隨意更改而不破壞簽名,從而防止篡改或欺詐。

-高效率:無需列印、簽署和掃描。 利用安全可靠的數位化審批,節省時間,簡化工作流程。

-信任:客戶和合作夥伴可以放心地驗證文件的來源和完整性。

簡而言之,數位簽章為您的文件工作流程帶來信任與效率

比較 iTextSharp 和 IronPDF

在 C# 中實作數位簽章時,通常有兩個函式庫會脫穎而出:iTextSharpIronPDF。 兩者都是功能強大的工具,但它們迎合了不同類型的開發人員和專案需求。 讓我們來分析一下它們在實際使用上的比較。

iTextSharp:強大的複雜性

iTextSharp 是 PDF 操作領域的知名品牌。 它是更廣泛的 iText 7 生態系統的一部分,提供廣泛的低階 PDF 作業支援,包括加密數位簽章。

需要對簽章外觀、散列演算法、憑證鏈和自訂驗證工作流程進行 精細控制的開發人員將會發現 iTextSharp 非常有能力。 它具有高度的可擴展性,在設計上也考慮到複雜的企業需求。

然而,這種靈活性是有代價的。學習曲線非常陡峭。簡單的工作,例如新增一個可見的簽章,往往需要多個類別、串流和設定步驟。 對於新使用者來說,這可能會令人不知所措。

此外,iTextSharp 採用 AGPL 授權,除非您購買商業授權,否則您的應用程式必須是開放原始碼的--這對許多封閉原始碼或專屬專案而言是個障礙。

IronPDF:簡單與專業的結合

IronPDF則採用現代化、開發者優先的方式。 其 API 旨在處理常見的 PDF 任務,例如數位簽章、生成、合併和編輯,只需最少的設定,使其成為 .NET Framework 專案的強大 PDF 函式庫。

例如,在 IronPDF 中簽署 PDF 不需要直接處理流或加密設定。 您只需載入 PDF,呼叫 SignPdf(),然後傳入您的憑證即可。 它甚至支援額外的元資料,例如簽名者的位置、原因和聯絡資訊,所有這些都可以透過單一方法呼叫完成。

另一個關鍵優點是授權。 IronPDF 提供不受 AGPL 限制的 commercial-friendly License,非常適合專業和企業級應用程式。 雖然這是一款付費產品,但優厚的免費試用版可讓您在使用前輕鬆評估。

並列摘要

特徵 iTextSharp IronPDF
易用性 陡峭的學習曲線 適合初學者,程式碼量極少
執照 AGPL (或付費商業授權) 無開源授權的商業授權
簽名自訂 高度客製化的加密控制 簡化的 API,帶有可選的元資料字段
說明文件 詳細但密集 清晰的範例和開發者導向的文檔
最適合 具有深度自訂功能的企業應用程式 需要快速實施和支援的團隊

開始使用 iTextSharp 和 IronPDF

在深入瞭解數位簽章實作之前,了解如何使用每個函式庫並開始運作是非常重要的。 無論您是要建立企業級的解決方案,或是快速的內部工具,正確的設定都能讓您事半功倍。

設定 iTextSharp

iTextSharp 是功能強大、基於 Java 的 iText PDF 函式庫的 .NET 移植。 要開始使用,您需要透過 NuGet 安裝,並在專案中引用正確的命名空間。

安裝

您可以透過 NuGet Package Manager 主控台輕鬆地將 iTextSharp 函式庫安裝到您的專案中。 您只需執行以下指令即可:

Install-Package iTextSharp

 安裝 iTextSharp

此簡易安裝方式可確保在您的 C# 專案中快速實作此函式庫。

基本設定

安裝完成後,您就可以開始在專案中使用 iTextSharp 命名空間:

using iTextSharp.text.pdf;
using iTextSharp.text.pdf.security;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.security;
Imports iTextSharp.text.pdf
Imports iTextSharp.text.pdf.security
$vbLabelText   $csharpLabel

請記住 iTextSharp 是模組化的。 如果您打算使用先進的加密功能或時間戳記,您可能需要額外的套件,例如 BouncyCastle.Cryptography.Cryptography。 安裝方式與 iTextSharp 相似,只要執行即可:

Install-Package BouncyCastle.Cryptography

注意事項

-授權: AGPL 授權要求任何使用 iTextSharp 的軟體都必須是開源的,除非您購買商業授權。

-依賴項:加密操作通常需要BouncyCastle進行證書處理。

-學習曲線:即使是基本的簽名也需要了解 PdfSignerIExternalSignature 和各種加密提供者。

如果您可以自如地設定這些建構區塊,並且需要完全控制簽署程序 (例如設定外觀、驗證等級或時間戳記伺服器),iTextSharp 會是一個可靠的選擇。

設定 IronPDF

IronPDF 是以開發人員生產力為考量而建立的商用 PDF 函式庫。 它專為想要以最少的麻煩產生、編輯和簽署 PDF 的 .NET 開發人員所設計。 IronPDF 提供了更順暢的上線體驗,特別是對於那些重視簡潔 API 和快速結果的人而言。

安裝

透過 NuGet 安裝最新的 IronPDF 套件:

Install-Package IronPdf

透過 NuGet 主控台安裝 IronPDF

或使用 .NET CLI:

Install-Package IronPdf

基本設定

從匯入 IronPDF 主命名空間開始:

using IronPdf;
using IronPdf;
Imports IronPdf
$vbLabelText   $csharpLabel

就這樣,您就可以載入 PDF 並開始新增數位簽章了。

IronPDF 在內部管理一切:證書載入、可見簽章定位、元資料和最終匯出。 您不必手動管理 PDF 串流或加密演算法,這對於快速開發而言是一大優勢。

初學者的主要優勢

-一體化:無需額外的依賴項或加密庫。

-無需擔心 AGPL 許可: IronPDF 提供永久許可和慷慨的免費試用。

-視覺渲染: IronPDF 能夠將 PDF 檔案渲染成與列印時完全相同的樣子,因此非常適合用於合約和官方文件。

逐步進行:新增數位簽章

1.準備您的證書

您需要一個 .pfx 數位憑證檔案和一個 密碼。 這些工具用來產生數位簽章。 您可以從可信賴的憑證授權機構 (CA) 取得憑證,或使用 OpenSSL 等工具產生內部使用的憑證。

2.使用 iTextSharp 和 BouncyCastle 進行 PDF 簽署

包含必要的名稱空間

首先,我們需要確保在程式碼頂端有正確的 using 語句,以便存取使用 iTextSharp 以數位方式簽署 PDF 所需的各種類別和方法。

using System;
using System.IO;
using System.Linq;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.security;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Pkcs;
using System;
using System.IO;
using System.Linq;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.security;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Pkcs;
Imports System
Imports System.IO
Imports System.Linq
Imports iTextSharp.text.pdf
Imports iTextSharp.text.pdf.security
Imports Org.BouncyCastle.Crypto
Imports Org.BouncyCastle.Pkcs
$vbLabelText   $csharpLabel

定義輸入 PDF 並將其載入 PdfReader

然後,我們指定現有 PDF 的路徑,並將其載入 PdfReader。 我們也會指定一些稍後會在程式碼中使用的字串變數。

// Path to the unsigned PDF you want to sign
string filename = "example.pdf";

// Load the existing PDF into a reader
PdfReader pdfReader = new PdfReader(filename);

string reason = "Digital Signature Reason";
string location = "Digital Signature Location";
// Path to the unsigned PDF you want to sign
string filename = "example.pdf";

// Load the existing PDF into a reader
PdfReader pdfReader = new PdfReader(filename);

string reason = "Digital Signature Reason";
string location = "Digital Signature Location";
' Path to the unsigned PDF you want to sign
Dim filename As String = "example.pdf"

' Load the existing PDF into a reader
Dim pdfReader As New PdfReader(filename)

Dim reason As String = "Digital Signature Reason"
Dim location As String = "Digital Signature Location"
$vbLabelText   $csharpLabel

定義憑證路徑和密碼

接下來,我們指向 .pfx 證書檔案,並提供用來保護它的密碼。

// Path to your .pfx certificate file (must contain private key)
string pfxFilePath = "certificate-file.pfx";

// Password for the certificate (make sure to protect this securely!)
string pfxPassword = "Password";
// Path to your .pfx certificate file (must contain private key)
string pfxFilePath = "certificate-file.pfx";

// Password for the certificate (make sure to protect this securely!)
string pfxPassword = "Password";
' Path to your .pfx certificate file (must contain private key)
Dim pfxFilePath As String = "certificate-file.pfx"

' Password for the certificate (make sure to protect this securely!)
Dim pfxPassword As String = "Password"
$vbLabelText   $csharpLabel

使用 Pkcs12Store 載入 .PFX 憑證

我們使用 BouncyCastle 將憑證和私人密碼匙載入安全的儲存空間。

// Initialize a new PKCS#12 key store (used for handling the PFX certificate)
Pkcs12StoreBuilder pkcs12StoreBuilder = new Pkcs12StoreBuilder();
Pkcs12Store pfxKeyStore = pkcs12StoreBuilder.Build();

// Load the certificate and private key from the PFX file
using (FileStream pfxStream = new FileStream(pfxFilePath, FileMode.Open, FileAccess.Read))
{
    // Load into the key store using the provided password
    pfxKeyStore.Load(pfxStream, pfxPassword.ToCharArray());
}
// Initialize a new PKCS#12 key store (used for handling the PFX certificate)
Pkcs12StoreBuilder pkcs12StoreBuilder = new Pkcs12StoreBuilder();
Pkcs12Store pfxKeyStore = pkcs12StoreBuilder.Build();

// Load the certificate and private key from the PFX file
using (FileStream pfxStream = new FileStream(pfxFilePath, FileMode.Open, FileAccess.Read))
{
    // Load into the key store using the provided password
    pfxKeyStore.Load(pfxStream, pfxPassword.ToCharArray());
}
' Initialize a new PKCS#12 key store (used for handling the PFX certificate)
Dim pkcs12StoreBuilder As New Pkcs12StoreBuilder()
Dim pfxKeyStore As Pkcs12Store = pkcs12StoreBuilder.Build()

' Load the certificate and private key from the PFX file
Using pfxStream As New FileStream(pfxFilePath, FileMode.Open, FileAccess.Read)
	' Load into the key store using the provided password
	pfxKeyStore.Load(pfxStream, pfxPassword.ToCharArray())
End Using
$vbLabelText   $csharpLabel

準備PdfStamper添加簽名

PdfStamper 可讓我們套用數位簽章,同時保留原始內容。

// Create a PdfStamper that enables signing and appends the signature to the document
PdfStamper pdfStamper = PdfStamper.CreateSignature(
    pdfReader,
    new FileStream("MyPDF_Signed.pdf", FileMode.Create), // Output path
    '\0',                                                // PDF version (unchanged)
    null,                                                // Temp file path (optional)
    true                                                 // Append mode (preserves original content)
);
// Create a PdfStamper that enables signing and appends the signature to the document
PdfStamper pdfStamper = PdfStamper.CreateSignature(
    pdfReader,
    new FileStream("MyPDF_Signed.pdf", FileMode.Create), // Output path
    '\0',                                                // PDF version (unchanged)
    null,                                                // Temp file path (optional)
    true                                                 // Append mode (preserves original content)
);
Imports Microsoft.VisualBasic

' Create a PdfStamper that enables signing and appends the signature to the document
Dim pdfStamper As PdfStamper = PdfStamper.CreateSignature(pdfReader, New FileStream("MyPDF_Signed.pdf", FileMode.Create), ControlChars.NullChar, Nothing, True)
$vbLabelText   $csharpLabel

自訂簽名外觀

現在我們定義簽名將如何以及在何處直觀地出現在文件中。

// Access the signature appearance settings
PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;

// Add optional metadata (shows up in PDF signature details)
signatureAppearance.Reason = reason;
signatureAppearance.Location = location;

// Position the visible signature on the page (x, y, width, height in points)
float x = 360;
float y = 130;
signatureAppearance.Acro6Layers = false;              // Use compact signature appearance
signatureAppearance.Layer4Text = PdfSignatureAppearance.QuestionMark; // Custom label text
signatureAppearance.SetVisibleSignature(
    new iTextSharp.text.Rectangle(x, y, x + 150, y + 50), // Rectangle position
    1,                                                    // Page number
    "signature"                                           // Field name
);
// Access the signature appearance settings
PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;

// Add optional metadata (shows up in PDF signature details)
signatureAppearance.Reason = reason;
signatureAppearance.Location = location;

// Position the visible signature on the page (x, y, width, height in points)
float x = 360;
float y = 130;
signatureAppearance.Acro6Layers = false;              // Use compact signature appearance
signatureAppearance.Layer4Text = PdfSignatureAppearance.QuestionMark; // Custom label text
signatureAppearance.SetVisibleSignature(
    new iTextSharp.text.Rectangle(x, y, x + 150, y + 50), // Rectangle position
    1,                                                    // Page number
    "signature"                                           // Field name
);
' Access the signature appearance settings
Dim signatureAppearance As PdfSignatureAppearance = pdfStamper.SignatureAppearance

' Add optional metadata (shows up in PDF signature details)
signatureAppearance.Reason = reason
signatureAppearance.Location = location

' Position the visible signature on the page (x, y, width, height in points)
Dim x As Single = 360
Dim y As Single = 130
signatureAppearance.Acro6Layers = False ' Use compact signature appearance
signatureAppearance.Layer4Text = PdfSignatureAppearance.QuestionMark ' Custom label text
signatureAppearance.SetVisibleSignature(New iTextSharp.text.Rectangle(x, y, x + 150, y + 50), 1, "signature")
$vbLabelText   $csharpLabel

擷取私密金鑰並簽署 PDF

我們擷取包含私密金鑰的憑證項目別名 (名稱)。 如果別名存在,我們會繼續使用 SHA-256 產生並內嵌數位簽章。

// Find the first alias in the PFX that has a private key entry
string alias = pfxKeyStore.Aliases.Cast<string>().FirstOrDefault(
    entryAlias => pfxKeyStore.IsKeyEntry(entryAlias)
);

// Ensure a valid alias (certificate) was found
if (alias != null)
{
    // Retrieve the private key for signing
    ICipherParameters privateKey = pfxKeyStore.GetKey(alias).Key;

    // Create a signer using SHA-256 and the private key
    IExternalSignature pks = new PrivateKeySignature(privateKey, DigestAlgorithms.SHA256);

    // Perform the digital signing operation using CMS format
    MakeSignature.SignDetached(
        signatureAppearance,     // Signature appearance
        pks,                     // External signature handler
        new Org.BouncyCastle.X509.X509Certificate[] {
            pfxKeyStore.GetCertificate(alias).Certificate
        },                       // Certificate chain (basic single-cert example)
        null, null, null,        // Optional CRL, OCSP, TSA
        0,                       // Estimated size for the signature (0 = auto)
        CryptoStandard.CMS       // Signature standard (CMS vs CAdES)
    );
}
else
{
    Console.WriteLine("Private key not found in the PFX certificate.");
}
// Find the first alias in the PFX that has a private key entry
string alias = pfxKeyStore.Aliases.Cast<string>().FirstOrDefault(
    entryAlias => pfxKeyStore.IsKeyEntry(entryAlias)
);

// Ensure a valid alias (certificate) was found
if (alias != null)
{
    // Retrieve the private key for signing
    ICipherParameters privateKey = pfxKeyStore.GetKey(alias).Key;

    // Create a signer using SHA-256 and the private key
    IExternalSignature pks = new PrivateKeySignature(privateKey, DigestAlgorithms.SHA256);

    // Perform the digital signing operation using CMS format
    MakeSignature.SignDetached(
        signatureAppearance,     // Signature appearance
        pks,                     // External signature handler
        new Org.BouncyCastle.X509.X509Certificate[] {
            pfxKeyStore.GetCertificate(alias).Certificate
        },                       // Certificate chain (basic single-cert example)
        null, null, null,        // Optional CRL, OCSP, TSA
        0,                       // Estimated size for the signature (0 = auto)
        CryptoStandard.CMS       // Signature standard (CMS vs CAdES)
    );
}
else
{
    Console.WriteLine("Private key not found in the PFX certificate.");
}
' Find the first alias in the PFX that has a private key entry
Dim [alias] As String = pfxKeyStore.Aliases.Cast(Of String)().FirstOrDefault(Function(entryAlias) pfxKeyStore.IsKeyEntry(entryAlias))

' Ensure a valid alias (certificate) was found
If [alias] IsNot Nothing Then
	' Retrieve the private key for signing
	Dim privateKey As ICipherParameters = pfxKeyStore.GetKey([alias]).Key

	' Create a signer using SHA-256 and the private key
	Dim pks As IExternalSignature = New PrivateKeySignature(privateKey, DigestAlgorithms.SHA256)

	' Perform the digital signing operation using CMS format
	MakeSignature.SignDetached(signatureAppearance, pks, New Org.BouncyCastle.X509.X509Certificate() { pfxKeyStore.GetCertificate([alias]).Certificate }, Nothing, Nothing, Nothing, 0, CryptoStandard.CMS)
Else
	Console.WriteLine("Private key not found in the PFX certificate.")
End If
$vbLabelText   $csharpLabel

完成文件

最後,我們關閉 stamper 以完成簽署程序,並將簽署的 PDF 寫入磁碟。

// Close the stamper to save and finalize the signed PDF
pdfStamper.Close();
// Close the stamper to save and finalize the signed PDF
pdfStamper.Close();
' Close the stamper to save and finalize the signed PDF
pdfStamper.Close()
$vbLabelText   $csharpLabel

輸出

 使用 iTextSharp 簽署 PDF

Bootstrap 安全配置表單

專業的 PDF 安全性需要直覺的設定介面。 此 Bootstrap 5 示例展示了 IronPDF 渲染具有验證状态和進度跟踪的多步骤安全配置表单的能力。

using IronPdf;

var renderer = new ChromePdfRenderer();

string securityConfigForm = @"
<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
    <style>
        .step-indicator { display: flex; justify-content: space-between; margin-bottom: 30px; }
        .step { flex: 1; text-align: center; position: relative; }
        .step-number { width: 40px; height: 40px; border-radius: 50%; background: #e9ecef;
            display: inline-flex; align-items: center; justify-content: center; font-weight: 700; }
        .step.completed .step-number { background: #198754; color: white; }
        .step.active .step-number { background: #0d6efd; color: white; }
        @media print { .form-section { page-break-inside: avoid; } }
    </style>
</head>
<body class='bg-light'>
    <div class='container py-4'>
        <div class='row justify-content-center'>
            <div class='col-lg-8'>
                <h2 class='text-center mb-4'>PDF Security Configuration</h2>

                <div class='step-indicator mb-4'>
                    <div class='step completed'>
                        <div class='step-number'>✓</div>
                        <div class='small mt-2'>Certificate</div>
                    </div>
                    <div class='step completed'>
                        <div class='step-number'>✓</div>
                        <div class='small mt-2'>Signature</div>
                    </div>
                    <div class='step active'>
                        <div class='step-number'>3</div>
                        <div class='small mt-2'>Encryption</div>
                    </div>
                    <div class='step'>
                        <div class='step-number'>4</div>
                        <div class='small mt-2'>Finalize</div>
                    </div>
                </div>

                <div class='card shadow-sm form-section'>
                    <div class='card-header bg-primary text-white'>
                        <h5 class='mb-0'>Step 3: Encryption & Permissions</h5>
                    </div>
                    <div class='card-body'>
                        <div class='mb-3'>
                            <label class='form-label'><strong>Encryption Level</strong></label>
                            <select class='form-select'>
                                <option>AES 128-bit</option>
                                <option selected>AES 256-bit (Recommended)</option>
                                <option>RC4 128-bit (Legacy)</option>
                            </select>
                            <small class='text-muted'>AES-256 provides enterprise-grade security</small>
                        </div>

                        <div class='mb-3'>
                            <label class='form-label'><strong>Document Permissions</strong></label>
                            <div class='form-check form-switch'>
                                <input class='form-check-input' type='checkbox' id='allowPrint' checked>
                                <label class='form-check-label' for='allowPrint'>Allow Printing</label>
                            </div>
                            <div class='form-check form-switch'>
                                <input class='form-check-input' type='checkbox' id='allowCopy'>
                                <label class='form-check-label' for='allowCopy'>Allow Content Copying</label>
                            </div>
                            <div class='form-check form-switch'>
                                <input class='form-check-input' type='checkbox' id='allowModify'>
                                <label class='form-check-label' for='allowModify'>Allow Document Modification</label>
                            </div>
                            <div class='form-check form-switch'>
                                <input class='form-check-input' type='checkbox' id='allowAnnotate' checked>
                                <label class='form-check-label' for='allowAnnotate'>Allow Annotations</label>
                            </div>
                        </div>

                        <div class='mb-3'>
                            <label class='form-label'><strong>Password Protection</strong></label>
                            <input type='password' class='form-control mb-2' placeholder='Owner Password' value='••••••••'>
                            <input type='password' class='form-control' placeholder='User Password (Optional)'>
                            <small class='text-muted'>Owner password controls document permissions</small>
                        </div>

                        <div class='alert alert-success'>
                            <strong>✓ Configuration Valid</strong><br>
                            <small>Security settings meet compliance requirements</small>
                        </div>
                    </div>
                    <div class='card-footer'>
                        <div class='d-flex justify-content-between'>
                            <button class='btn btn-outline-secondary'>← Previous</button>
                            <button class='btn btn-primary'>Continue →</button>
                        </div>
                    </div>
                </div>

                <div class='card mt-3 shadow-sm'>
                    <div class='card-body'>
                        <h6 class='text-primary'>Security Comparison</h6>
                        <div class='row g-2'>
                            <div class='col-6'>
                                <div class='text-center p-2 bg-success text-white rounded'>
                                    <strong>IronPDF</strong><br>
                                    <small>AES-256 Native</small>
                                </div>
                            </div>
                            <div class='col-6'>
                                <div class='text-center p-2 bg-warning text-dark rounded'>
                                    <strong>iTextSharp</strong><br>
                                    <small>Complex Setup</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>";

var pdf = renderer.RenderHtmlAsPdf(securityConfigForm);
pdf.SaveAs("security-configuration.pdf");
using IronPdf;

var renderer = new ChromePdfRenderer();

string securityConfigForm = @"
<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
    <style>
        .step-indicator { display: flex; justify-content: space-between; margin-bottom: 30px; }
        .step { flex: 1; text-align: center; position: relative; }
        .step-number { width: 40px; height: 40px; border-radius: 50%; background: #e9ecef;
            display: inline-flex; align-items: center; justify-content: center; font-weight: 700; }
        .step.completed .step-number { background: #198754; color: white; }
        .step.active .step-number { background: #0d6efd; color: white; }
        @media print { .form-section { page-break-inside: avoid; } }
    </style>
</head>
<body class='bg-light'>
    <div class='container py-4'>
        <div class='row justify-content-center'>
            <div class='col-lg-8'>
                <h2 class='text-center mb-4'>PDF Security Configuration</h2>

                <div class='step-indicator mb-4'>
                    <div class='step completed'>
                        <div class='step-number'>✓</div>
                        <div class='small mt-2'>Certificate</div>
                    </div>
                    <div class='step completed'>
                        <div class='step-number'>✓</div>
                        <div class='small mt-2'>Signature</div>
                    </div>
                    <div class='step active'>
                        <div class='step-number'>3</div>
                        <div class='small mt-2'>Encryption</div>
                    </div>
                    <div class='step'>
                        <div class='step-number'>4</div>
                        <div class='small mt-2'>Finalize</div>
                    </div>
                </div>

                <div class='card shadow-sm form-section'>
                    <div class='card-header bg-primary text-white'>
                        <h5 class='mb-0'>Step 3: Encryption & Permissions</h5>
                    </div>
                    <div class='card-body'>
                        <div class='mb-3'>
                            <label class='form-label'><strong>Encryption Level</strong></label>
                            <select class='form-select'>
                                <option>AES 128-bit</option>
                                <option selected>AES 256-bit (Recommended)</option>
                                <option>RC4 128-bit (Legacy)</option>
                            </select>
                            <small class='text-muted'>AES-256 provides enterprise-grade security</small>
                        </div>

                        <div class='mb-3'>
                            <label class='form-label'><strong>Document Permissions</strong></label>
                            <div class='form-check form-switch'>
                                <input class='form-check-input' type='checkbox' id='allowPrint' checked>
                                <label class='form-check-label' for='allowPrint'>Allow Printing</label>
                            </div>
                            <div class='form-check form-switch'>
                                <input class='form-check-input' type='checkbox' id='allowCopy'>
                                <label class='form-check-label' for='allowCopy'>Allow Content Copying</label>
                            </div>
                            <div class='form-check form-switch'>
                                <input class='form-check-input' type='checkbox' id='allowModify'>
                                <label class='form-check-label' for='allowModify'>Allow Document Modification</label>
                            </div>
                            <div class='form-check form-switch'>
                                <input class='form-check-input' type='checkbox' id='allowAnnotate' checked>
                                <label class='form-check-label' for='allowAnnotate'>Allow Annotations</label>
                            </div>
                        </div>

                        <div class='mb-3'>
                            <label class='form-label'><strong>Password Protection</strong></label>
                            <input type='password' class='form-control mb-2' placeholder='Owner Password' value='••••••••'>
                            <input type='password' class='form-control' placeholder='User Password (Optional)'>
                            <small class='text-muted'>Owner password controls document permissions</small>
                        </div>

                        <div class='alert alert-success'>
                            <strong>✓ Configuration Valid</strong><br>
                            <small>Security settings meet compliance requirements</small>
                        </div>
                    </div>
                    <div class='card-footer'>
                        <div class='d-flex justify-content-between'>
                            <button class='btn btn-outline-secondary'>← Previous</button>
                            <button class='btn btn-primary'>Continue →</button>
                        </div>
                    </div>
                </div>

                <div class='card mt-3 shadow-sm'>
                    <div class='card-body'>
                        <h6 class='text-primary'>Security Comparison</h6>
                        <div class='row g-2'>
                            <div class='col-6'>
                                <div class='text-center p-2 bg-success text-white rounded'>
                                    <strong>IronPDF</strong><br>
                                    <small>AES-256 Native</small>
                                </div>
                            </div>
                            <div class='col-6'>
                                <div class='text-center p-2 bg-warning text-dark rounded'>
                                    <strong>iTextSharp</strong><br>
                                    <small>Complex Setup</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>";

var pdf = renderer.RenderHtmlAsPdf(securityConfigForm);
pdf.SaveAs("security-configuration.pdf");
Imports IronPdf

Dim renderer As New ChromePdfRenderer()

Dim securityConfigForm As String = "
<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <link href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css' rel='stylesheet'>
    <style>
        .step-indicator { display: flex; justify-content: space-between; margin-bottom: 30px; }
        .step { flex: 1; text-align: center; position: relative; }
        .step-number { width: 40px; height: 40px; border-radius: 50%; background: #e9ecef;
            display: inline-flex; align-items: center; justify-content: center; font-weight: 700; }
        .step.completed .step-number { background: #198754; color: white; }
        .step.active .step-number { background: #0d6efd; color: white; }
        @media print { .form-section { page-break-inside: avoid; } }
    </style>
</head>
<body class='bg-light'>
    <div class='container py-4'>
        <div class='row justify-content-center'>
            <div class='col-lg-8'>
                <h2 class='text-center mb-4'>PDF Security Configuration</h2>

                <div class='step-indicator mb-4'>
                    <div class='step completed'>
                        <div class='step-number'>✓</div>
                        <div class='small mt-2'>Certificate</div>
                    </div>
                    <div class='step completed'>
                        <div class='step-number'>✓</div>
                        <div class='small mt-2'>Signature</div>
                    </div>
                    <div class='step active'>
                        <div class='step-number'>3</div>
                        <div class='small mt-2'>Encryption</div>
                    </div>
                    <div class='step'>
                        <div class='step-number'>4</div>
                        <div class='small mt-2'>Finalize</div>
                    </div>
                </div>

                <div class='card shadow-sm form-section'>
                    <div class='card-header bg-primary text-white'>
                        <h5 class='mb-0'>Step 3: Encryption & Permissions</h5>
                    </div>
                    <div class='card-body'>
                        <div class='mb-3'>
                            <label class='form-label'><strong>Encryption Level</strong></label>
                            <select class='form-select'>
                                <option>AES 128-bit</option>
                                <option selected>AES 256-bit (Recommended)</option>
                                <option>RC4 128-bit (Legacy)</option>
                            </select>
                            <small class='text-muted'>AES-256 provides enterprise-grade security</small>
                        </div>

                        <div class='mb-3'>
                            <label class='form-label'><strong>Document Permissions</strong></label>
                            <div class='form-check form-switch'>
                                <input class='form-check-input' type='checkbox' id='allowPrint' checked>
                                <label class='form-check-label' for='allowPrint'>Allow Printing</label>
                            </div>
                            <div class='form-check form-switch'>
                                <input class='form-check-input' type='checkbox' id='allowCopy'>
                                <label class='form-check-label' for='allowCopy'>Allow Content Copying</label>
                            </div>
                            <div class='form-check form-switch'>
                                <input class='form-check-input' type='checkbox' id='allowModify'>
                                <label class='form-check-label' for='allowModify'>Allow Document Modification</label>
                            </div>
                            <div class='form-check form-switch'>
                                <input class='form-check-input' type='checkbox' id='allowAnnotate' checked>
                                <label class='form-check-label' for='allowAnnotate'>Allow Annotations</label>
                            </div>
                        </div>

                        <div class='mb-3'>
                            <label class='form-label'><strong>Password Protection</strong></label>
                            <input type='password' class='form-control mb-2' placeholder='Owner Password' value='••••••••'>
                            <input type='password' class='form-control' placeholder='User Password (Optional)'>
                            <small class='text-muted'>Owner password controls document permissions</small>
                        </div>

                        <div class='alert alert-success'>
                            <strong>✓ Configuration Valid</strong><br>
                            <small>Security settings meet compliance requirements</small>
                        </div>
                    </div>
                    <div class='card-footer'>
                        <div class='d-flex justify-content-between'>
                            <button class='btn btn-outline-secondary'>← Previous</button>
                            <button class='btn btn-primary'>Continue →</button>
                        </div>
                    </div>
                </div>

                <div class='card mt-3 shadow-sm'>
                    <div class='card-body'>
                        <h6 class='text-primary'>Security Comparison</h6>
                        <div class='row g-2'>
                            <div class='col-6'>
                                <div class='text-center p-2 bg-success text-white rounded'>
                                    <strong>IronPDF</strong><br>
                                    <small>AES-256 Native</small>
                                </div>
                            </div>
                            <div class='col-6'>
                                <div class='text-center p-2 bg-warning text-dark rounded'>
                                    <strong>iTextSharp</strong><br>
                                    <small>Complex Setup</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>"

Dim pdf = renderer.RenderHtmlAsPdf(securityConfigForm)
pdf.SaveAs("security-configuration.pdf")
$vbLabelText   $csharpLabel

輸出:一個專業的安全設定表單 PDF,帶有 Bootstrap 5 步驟指示器、表單控制項、開關和驗證警報。 IronPDF 以完美的保真度渲染了所有表單樣式、實用類和互動元素,與 iTextSharp 的程式化方法相比,展現了卓越的表單渲染能力。

有關 Bootstrap 表單支援的詳細資訊,請參閱 Bootstrap & Flexbox CSS 指南

3. 使用 IronPDF 在 C# 中對 PDF 進行數位簽章

包含必要的名稱空間

我們首先匯入必要的命名空間,以便處理 PDF 簽署、證書處理和影像定位。

using IronPdf;
using IronPdf.Signing;
using IronSoftware.Drawing;
using System.Security.Cryptography.X509Certificates;
using IronPdf;
using IronPdf.Signing;
using IronSoftware.Drawing;
using System.Security.Cryptography.X509Certificates;
Imports IronPdf
Imports IronPdf.Signing
Imports IronSoftware.Drawing
Imports System.Security.Cryptography.X509Certificates
$vbLabelText   $csharpLabel

載入您要簽署的 PDF 文件

我們使用 IronPDF 簡單的 PdfDocument API 從磁碟載入現有的 PDF 檔案。 您也可以為此任務建立新的 PDF 文件。

var pdf = PdfDocument.FromFile("example.pdf");
var pdf = PdfDocument.FromFile("example.pdf");
Dim pdf = PdfDocument.FromFile("example.pdf")
$vbLabelText   $csharpLabel

載入用於簽署的 PFX 證書

我們載入包含私密金鑰的 .pfx 證書。 需要使用 Exportable 標誌,以便存取簽章金鑰。

X509Certificate2 cert = new X509Certificate2(
    "IronSoftware.pfx",
    "Password",
    X509KeyStorageFlags.Exportable
);
X509Certificate2 cert = new X509Certificate2(
    "IronSoftware.pfx",
    "Password",
    X509KeyStorageFlags.Exportable
);
Dim cert As New X509Certificate2("IronSoftware.pfx", "Password", X509KeyStorageFlags.Exportable)
$vbLabelText   $csharpLabel

使用證書建立新的 PdfSignature

我們從載入的憑證建立一個新的 PdfSignature 物件。

var sig = new PdfSignature(cert);
var sig = new PdfSignature(cert);
Dim sig = New PdfSignature(cert)
$vbLabelText   $csharpLabel

套用簽章並儲存輸出

我們對 PDF 進行數位簽章,並將簽章後的 PDF 文件儲存為新檔案。

pdf.Sign(sig);
pdf.SaveAs("signed.pdf");
pdf.Sign(sig);
pdf.SaveAs("signed.pdf");
pdf.Sign(sig)
pdf.SaveAs("signed.pdf")
$vbLabelText   $csharpLabel

輸出

 使用 IronPDF 簽署的 PDF

4.程式碼解釋

  • IronPDF讓簽署過程簡單易讀。 您載入 PDF 文件,提供證書,然後撥打 SignPdf()。 可選的元資料(聯絡人、地點、原因)增加了專業性。

  • iTextSharp 提供了更多的控制功能,但需要對雜湊演算法、串流和憑證鏈進行詳細設定。

摘要:僅需幾行程式碼,IronPDF 即可使用標準 .pfx 證書輕鬆套用數位簽章 - 無需低階加密技術。 相較於 iTextSharp 等程式庫處理相同工作所需的冗長程式碼,這使其更容易實作。

5.真實世界的使用案例

-法務團隊:自動簽署根據範本產生的合約。

-財務:對發票和報告進行電子簽名,以防止篡改。

-政府入口網站:提交表格前請先簽名,以符合監管標準。

數位簽章的最佳實務

為了讓您的數位簽章實作發揮最大功效:

-使用強憑證:選擇 2048 位元 RSA 金鑰或更強的金鑰。

-保護私鑰安全:安全地儲存證書,最好儲存在硬體安全模組 (HSM) 中。

-為您的簽章新增時間戳記:新增可信任時間戳,以確保即使憑證過期,簽章仍然有效。

-驗證簽章:在您的應用程式中加入驗證功能,以偵測竄改或過期的憑證。

-自動化:在部署管道中安排簽章操作,以確保文件完整性的一致性。

結論

在 PDF 文件中加入數位簽章不再是奢侈品,而是現今注重安全的數位環境中的必需品。 無論您要保護的是合約、發票、報告或法律文件,有可信賴的憑證支援的防偽簽章都能確保您的檔案保持其真實性和完整性。

在這篇文章中,我們探討了 C# 中兩種強大的 PDF 簽署方法:

  • iTextSharp,它可以為您提供低階密碼控制和靈活性,但需要更多的模板和熟悉 BouncyCastle。

  • IronPDF提供了一個現代化的、高級的 API,使應用安全簽名的過程流暢且對開發人員友好。

這兩種工具都支援安全的 .pfx 憑證,但 IronPDF 明顯地簡化了工作流程 - 對於希望花較少時間處理加密原語,花較多時間提供業務價值的 .NET 開發人員來說是理想之選。

iTextSharp vs IronPDF 比較圖

下一步

如果您尚未下載,請考慮下載 IronPDF 免費試用版,並嘗試用幾行程式碼簽署您自己的 PDF。 光是生產力的提升就值得轉換,尤其是在處理時間敏感的專案時。

請注意iTextSharp 是其各自所有者的註冊商標。 本網站與 iTextSharp 無任何關聯、背書或贊助。所有產品名稱、標誌和品牌均為其各自所有者的財產。 比較僅供參考,反映了撰寫時的公開信息。

常見問題解答

數位簽章如何確保 PDF 文件的真實性?

數位簽章使用加密技術來驗證簽署者的身份,並確保文件沒有被更改。這是通過使用私鑰加密文件的雜湊來實現的,提供認證和完整性。

為什麼數位簽章對電子文件很重要?

數位簽章對於維護電子文件的合法性、安全性、效率和信任至關重要。它們確保遵守規定、防止篡改、簡化文件工作流程並確認文件的來源和完整性。

如何在 C# 中將數位簽章新增到 PDF?

在 C# 中,您可以使用 IronPDF 來為 PDF 新增數位簽章。該過程包括加載 PDF,通過 X509Certificate2 提供 .pfx 證書,並調用 Sign 方法來應用簽章。

iTextSharp 與另一個 PDF 庫在數位簽章方面的主要區別是什麼?

iTextSharp 提供詳細的 PDF 操作的廣泛支持,具有陡峭的學習曲線並需要特定的許可。相比之下,IronPDF 對初學者友好,具有簡化的 API,允許快速實施,且不需要開源許可。

如何為 C# 中的文件簽署安裝 PDF 庫?

您可以通過使用命令 Install-Package IronPDF 或透過 .NET CLI 使用 dotnet add package IronPDF 來安裝 IronPDF。

使用 iTextSharp 要將 PDF 進行數位簽署需要哪些步驟?

要使用 iTextSharp 使用數位簽署 PDF,您需要配置 PdfStamper,自訂簽章外觀,使用 BouncyCastle 加載 .pfx 證書,並利用 PdfSignerIExternalSignature 進行加密操作。

在 PDF 中實行數位簽章的一些最佳實踐是什麼?

最佳實踐包括使用強大的證書、保護私鑰、為簽章加上時間戳、定期驗證簽章以及自動化簽名過程以維持文件的完整性。

數位簽章在 PDF 文件中的一些實際應用是什麼?

數位簽章通常用於法律部門的合同簽署,在金融業的核准發票和報告,及政府機構的處理表單中,以確保符合監管標準。

哪個 PDF 庫更適合需要快速實現數位簽章的開發人員?

對於尋求快速實施數位簽章的開發人員,推薦使用 IronPDF,因為它具有簡單和乾淨的 API,簡化了簽署過程,所需代碼最少。

IronPDF 是否與 .NET 10 相容,可以用來新增和驗證數位簽章?

是 - IronPDF 與 .NET 10 完全相容。它支援 .NET10(以及 .NET9、8、7 等),其數位簽章功能(例如使用 PdfSignature, X509Certificate2, 簽署與驗證)在 .NET 10 runtime 上開箱即用。

Curtis Chau
技術作家

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

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

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我