跳至頁尾內容
產品對比
如何使用 ITextSharp 在 C# 中為 PDF 新增數位簽名

使用 iTextSharp 在 C# 中為 PDF 新增數位簽名

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

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

了解數位簽名

數位簽章是一種加密技術,用於驗證數位資訊或文件的真實性和完整性。 與簡單的圖像簽署或鍵入的姓名不同,數位簽章使用私鑰對文件的雜湊值進行加密。 任何人都可以使用簽署者的公鑰來驗證這個加密哈希值。

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

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

2.完整性-該文件自簽署以來未被更改。 即使是微小的改動也會使簽名失效。

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

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

從法律合約到官方報告,PDF 是分發專業文件的標準格式。 在PDF文件中加入數位簽章有幾個關鍵用途:

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

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

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

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

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

iTextSharp 和 IronPDF 的比較

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

iTextSharp:駕馭複雜性的強大功能

iTextSharp是 PDF 處理領域內一個家喻戶曉的名字。 它是 iText 7 生態系統的一部分,為底層 PDF 操作提供廣泛的支持,包括加密數位簽章。

對於需要對簽章外觀、雜湊演算法、憑證鍊和自訂驗證工作流程進行精細控制的開發人員來說,iTextSharp 的功能非常強大。 它具有高度可擴展性,並且在設計時充分考慮了複雜的企業需求。

然而,這種靈活性是有代價的。學習曲線非常陡峭。即使是新增可見簽章這樣簡單的任務,通常也需要多個類別、流和設定步驟。 對於新用戶來說,這可能會讓人不知所措。

此外,iTextSharp 採用 AGPL 許可,這意味著除非您購買商業許可,否則您的應用程式必須是開源的——這對許多閉源或專有專案來說是一個致命的缺陷。

IronPDF:簡約與專業兼備

相較之下, IronPDF採用了一種現代化的、以開發者為先的方法。 它的 API 旨在以最少的設定處理常見的 PDF 任務(如數位簽章、產生、合併和編輯),使其成為 .NET 框架專案的強大 PDF 庫。

例如,在 IronPDF 中簽署 PDF 檔案不需要直接操作流程或加密設定。 您只需載入 PDF 文件,呼叫SignPdf()函數,然後傳入您的憑證即可。 它甚至支援額外的元數據,例如簽署者的位置、原因和聯絡資訊——所有這些都可以在一次方法呼叫中完成。

另一個關鍵優勢是授權許可。 IronPDF 提供商業用途友善的許可證,沒有 AGPL 限制,非常適合專業級和企業級應用程式。 雖然這是一款付費產品,但它提供了慷慨的免費試用期,讓用戶在決定購買前可以輕鬆進行評估。

並排摘要

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

iTextSharp 和 IronPDF 入門指南

在深入研究數位簽章實作之前,了解如何快速上手使用每個函式庫至關重要。 無論您是建立企業級解決方案還是快速開發內部工具,正確的設定都能發揮至關重要的作用。

設定 iTextSharp

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

安裝

您可以透過 NuGet 套件管理器控制台輕鬆地將 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;
$vbLabelText   $csharpLabel

請記住,iTextSharp 是模組化的。 如果您打算使用進階加密功能或時間戳,您可能需要像 BouncyCastle.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;
$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;
$vbLabelText   $csharpLabel

定義輸入PDF並將其載入到PDF閱讀器中

然後我們指定現有 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";
$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";
$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());
}
$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)
);
$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
);
$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.");
}
$vbLabelText   $csharpLabel

完成文件

最後,我們關閉印章完成簽名過程,並將簽署後的 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();
$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");
$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;
$vbLabelText   $csharpLabel

載入您要簽署的PDF文件

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

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

載入用於簽署的 PFX 證書

我們載入包含私鑰的 .pfx 憑證。 必須啟用"可匯出"標誌才能存取簽署金鑰。

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

使用憑證建立新的 PdfSignature

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

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

應用簽名並保存輸出

我們對 PDF 文件進行數位簽名,並將簽名後的 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 開發人員來說,IronPDF 是理想之選。

iTextSharp 與 IronPDF 比較圖表

後續步驟

如果您還沒有嘗試過,不妨下載IronPDF 的免費試用版,只需幾行程式碼即可嘗試對您自己的 PDF 檔案進行簽名。 光是生產力的提升就值得做出改變,尤其是在處理有時效性的項目時。

請注意iTextSharp 是其各自所有者的註冊商標。 本網站與iTextSharp無任何關聯,亦未獲得其認可或贊助。所有產品名稱、標誌和品牌均為其各自所有者的財產。 文中比較僅供參考,反映的是撰寫本文時可公開取得的資訊。

常見問題解答

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

數位簽章利用加密技術來驗證簽署者的身份,並確保文件未被竄改。其原理是使用私鑰對文件的雜湊值進行加密,從而同時提供身份驗證和完整性保障。

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

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

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

在 C# 中,可以使用 IronPDF 為 PDF 新增數位簽章。過程包括載入 PDF 文件,使用X509Certificate2提供 .pfx 證書,然後呼叫Sign方法來套用簽章。

iTextSharp 與其他用於數位簽章的 PDF 函式庫的主要差異是什麼?

iTextSharp 提供對複雜 PDF 操作的全面支持,但學習曲線陡峭,且需要特定許可證。相比之下,IronPDF 對初學者友好,API 簡化,易於快速部署,且無需開源許可證。

如何在C#中安裝用於文件簽章的PDF庫?

您可以使用 NuGet 指令安裝 IronPDF: Install-Package IronPdf ,或使用 .NET CLI 的dotnet add package IronPdf

使用 iTextSharp 對 PDF 檔案進行數位簽章需要哪些步驟?

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

在PDF中實施數位簽章有哪些最佳實務?

最佳實踐包括使用強證書、保護私鑰、在簽名中添加時間戳記、定期驗證簽名以及自動化簽名過程以維護文件完整性。

數位簽章在PDF文件中有哪些實際應用?

數位簽名通常用於法律部門簽署合約、財務部門批准發票和報告,以及政府機構處理表格以確保符合監管標準。

對於需要快速實現數位簽章的開發人員來說,哪個 PDF 庫更好?

對於尋求快速實現數位簽章的開發人員來說,IronPDF 是一個不錯的選擇,因為它具有簡單明了的 API,可以簡化簽名過程,並且只需要極少的程式碼。

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

是的-IronPDF 與 .NET 10 完全相容。它支援 .NET 10(以及 .NET 9、8、7 等),其數位簽章功能(例如使用PdfSignatureX509Certificate2 、簽章和驗證)在 .NET 10 執行階段中開箱即用。

柯蒂斯·週
技術撰稿人

Curtis Chau擁有卡爾頓大學電腦科學學士學位,專長於前端開發,精通Node.js、TypeScript、JavaScript和React。他熱衷於打造直覺美觀的使用者介面,喜歡使用現代框架,並擅長撰寫結構清晰、視覺效果出色的使用者手冊。

除了開發工作之外,柯蒂斯對物聯網 (IoT) 也抱有濃厚的興趣,致力於探索硬體和軟體整合的創新方法。閒暇時,他喜歡玩遊戲和製作 Discord 機器人,將他對科技的熱愛與創造力結合。