跳過到頁腳內容
產品比較

PDFsharp數位簽名文檔與IronPDF(代碼示例)

數位簽章是一種數學技術,可驗證電子文件的真實性和完整性。 它可作為電子簽章,在多個司法管轄區內以數位方式簽署文件,確保極高的安全性和法律效力。

數位簽章是使用私密金鑰建立的,而私密金鑰只有簽章者知道。 此私密金鑰會在簽署文件時建立與文件連結的唯一數位簽章。 簽名包括簽名者的姓名、電子郵件地址和其他個人資訊。 為了確認數位簽章文件的真實性,接收者需要存取簽章者的公開金鑰。 簽章的合法性可透過使用公開金鑰進行解密來驗證。

在本教程中,我們將比較如何使用 PDFSharpIronPDF 為 PDF 文件新增數位簽章。 數位簽章是驗證文件真偽的必要條件,而 PDF 檔案是此類作業的常用格式。

PDFsharp 是一個知名的開放原始碼資料庫,用於 PDF 的建立與操作,而 IronPDF 則是一個強大的 .NET PDF 資料庫,提供類似的功能與額外的進階功能。

本指南涵蓋使用私密金鑰簽署 PDF 文件和驗證簽章,以及兩個函式庫的範例原始碼。

數位簽章為何重要?

數位簽章可確保文件的完整性,並提供強大的安全性。 這些工具常用於合約、協議和其他法律文件。

主要優點:

  • 比傳統簽名更安全、防竄改。
  • 以電子方式驗證,減少人工驗證的工作。
  • 在全球範圍內啟用遠端簽署文件。
  • 提供比傳統簽名更大的保證。

PDFsharp 概述

PDFSharp 是一個開放原始碼的 C# 函式庫,主要用於建立和處理 PDF 文件。 它被廣泛用於基本的 PDF 任務,例如產生簡單的 PDF 檔案、編輯現有文件以及渲染圖形。 目前,.NET、Java、Python 或 Node js 已經成為開發人員的主要工具,但其對於數位簽章等進階功能的原生支援有限,開發人員通常需要仰賴第三方函式庫 (例如 BouncyCastle) 來整合這些功能。 PDFsharp 採用 MIT 授權,是開放原始碼的軟體,因此對於以成本和彈性為優先考量的專案而言,PDFsharp 是不錯的選擇。

主要功能

  • 在 MIT 授權下開放原始碼且免費。
  • 基本的 PDF 建立與操作。
  • 可使用外部函式庫進行擴充,如用於數位簽章的 BouncyCastle。
  • 缺乏對進階 PDF 功能的開箱即用支援,例如 HTML 到 PDF 的轉換和複雜的表單處理。

IronPDF 概述

PDFsharp 以數位方式簽署 PDF 文件 vs IronPDF (程式碼範例):圖 1 - image.png

IronPDF 是一個強大的 .NET PDF 函式庫,提供簡單且功能強大的 API 來產生、編輯和處理 PDF。 其突出的功能之一是開發人員可以輕鬆實現數位簽署,這對驗證文件的真實性非常重要。 除了數位簽章之外,IronPDF 還支援進階功能,例如 HTML-to-PDF轉換、水印和表單處理。 對於從事商業專案的開發人員尤其有價值,因為在商業專案中,快速執行和強大的功能是優先考量。

主要功能

  • 提供付費支援的商業授權,以及免費試用版。
  • 易於使用的 API,具有現代化的 數位簽署和文件操作功能。
  • 包括對 HTML 至 PDF 格式轉換、表單處理PDF 註釋(例如附件註釋)的內建支援。
  • 與時間戳記、視覺簽章影像和 加密等先進功能的無縫整合。

使用 PDFsharp 程式化地新增數位簽章。

PDFsharp 是一個開放原始碼的函式庫,專為在 C# 中建立和處理 PDF 而設計。 不過,雖然它確實提供了加入簽名的支援,但您需要整合第三方工具,如 BouncyCastle,以確保 PDF 文件安全、準確的數位簽署。

使用 PDFsharp 新增數位簽章的步驟

1.透過 NuGet 安裝 PDFsharp 和 BouncyCastle。 2.使用 X509Certificate2 建立數位憑證。 3.使用 BouncyCastle 簽署 PDF

範例程式碼

using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using BouncyCastleSigner; // Hypothetical namespace for illustration
// Ensure that you have the appropriate namespaces added

class Program
{
    static void Main(string[] args)
    {
        // Create a font for the appearance of the signature
        var font = new XFont("Verdana", 10.0, XFontStyle.Regular);

        // Create a new PDF document
        var document = new PdfDocument();
        var pdfPage = document.AddPage();

        // Prepare graphics for drawing on the PDF page
        var xGraphics = XGraphics.FromPdfPage(pdfPage);
        var layoutRectangle = new XRect(0.0, 0.0, pdfPage.Width.Point, pdfPage.Height.Point);

        // Add some text to the page
        xGraphics.DrawString("Signed sample document", font, XBrushes.Black, layoutRectangle, XStringFormats.TopCenter);

        // Define digital signature appearance options
        var options = new DigitalSignatureOptions
        {
            ContactInfo = "John Doe",
            Location = "Seattle",
            Reason = "License Agreement",
            Rectangle = new XRect(36.0, 700.0, 400.0, 50.0),
            AppearanceHandler = new SignatureAppearanceHandler()
        };

        // Sign the document using BouncyCastle signer
        var pdfSignatureHandler = DigitalSignatureHandler.ForDocument(document,
            new PdfSharp.Snippets.Pdf.BouncyCastleSigner(GetCertificate(), PdfMessageDigestType.SHA256), options);

        // Save the signed document
        document.Save("PdfSharpSignature.pdf");
    }

    static (X509Certificate2, X509Certificate2Collection) GetCertificate()
    {
        // Locate the certificate file and read its data
        var certFolder = "C:\\Users\\kyess\\AppData\\Roaming\\Adobe\\Acrobat\\DC\\Security";
        var pfxFile = Path.Combine(certFolder, "IronSoftware.pfx");
        var rawData = File.ReadAllBytes(pfxFile);

        // Load the certificate using its password (example password)
        var certificatePassword = "Passw0rd";
        var certificate = new X509Certificate2(rawData, certificatePassword,
            X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

        // Create and return the certificate collection
        var collection = new X509Certificate2Collection();
        collection.Import(rawData, certificatePassword,
            X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
        return (certificate, collection);
    }
}
using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using BouncyCastleSigner; // Hypothetical namespace for illustration
// Ensure that you have the appropriate namespaces added

class Program
{
    static void Main(string[] args)
    {
        // Create a font for the appearance of the signature
        var font = new XFont("Verdana", 10.0, XFontStyle.Regular);

        // Create a new PDF document
        var document = new PdfDocument();
        var pdfPage = document.AddPage();

        // Prepare graphics for drawing on the PDF page
        var xGraphics = XGraphics.FromPdfPage(pdfPage);
        var layoutRectangle = new XRect(0.0, 0.0, pdfPage.Width.Point, pdfPage.Height.Point);

        // Add some text to the page
        xGraphics.DrawString("Signed sample document", font, XBrushes.Black, layoutRectangle, XStringFormats.TopCenter);

        // Define digital signature appearance options
        var options = new DigitalSignatureOptions
        {
            ContactInfo = "John Doe",
            Location = "Seattle",
            Reason = "License Agreement",
            Rectangle = new XRect(36.0, 700.0, 400.0, 50.0),
            AppearanceHandler = new SignatureAppearanceHandler()
        };

        // Sign the document using BouncyCastle signer
        var pdfSignatureHandler = DigitalSignatureHandler.ForDocument(document,
            new PdfSharp.Snippets.Pdf.BouncyCastleSigner(GetCertificate(), PdfMessageDigestType.SHA256), options);

        // Save the signed document
        document.Save("PdfSharpSignature.pdf");
    }

    static (X509Certificate2, X509Certificate2Collection) GetCertificate()
    {
        // Locate the certificate file and read its data
        var certFolder = "C:\\Users\\kyess\\AppData\\Roaming\\Adobe\\Acrobat\\DC\\Security";
        var pfxFile = Path.Combine(certFolder, "IronSoftware.pfx");
        var rawData = File.ReadAllBytes(pfxFile);

        // Load the certificate using its password (example password)
        var certificatePassword = "Passw0rd";
        var certificate = new X509Certificate2(rawData, certificatePassword,
            X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

        // Create and return the certificate collection
        var collection = new X509Certificate2Collection();
        collection.Import(rawData, certificatePassword,
            X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
        return (certificate, collection);
    }
}
Imports System
Imports System.IO
Imports System.Security.Cryptography.X509Certificates
Imports PdfSharp.Drawing
Imports PdfSharp.Pdf
Imports BouncyCastleSigner ' Hypothetical namespace for illustration
' Ensure that you have the appropriate namespaces added

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create a font for the appearance of the signature
		Dim font = New XFont("Verdana", 10.0, XFontStyle.Regular)

		' Create a new PDF document
		Dim document = New PdfDocument()
		Dim pdfPage = document.AddPage()

		' Prepare graphics for drawing on the PDF page
		Dim xGraphics = XGraphics.FromPdfPage(pdfPage)
		Dim layoutRectangle = New XRect(0.0, 0.0, pdfPage.Width.Point, pdfPage.Height.Point)

		' Add some text to the page
		xGraphics.DrawString("Signed sample document", font, XBrushes.Black, layoutRectangle, XStringFormats.TopCenter)

		' Define digital signature appearance options
		Dim options = New DigitalSignatureOptions With {
			.ContactInfo = "John Doe",
			.Location = "Seattle",
			.Reason = "License Agreement",
			.Rectangle = New XRect(36.0, 700.0, 400.0, 50.0),
			.AppearanceHandler = New SignatureAppearanceHandler()
		}

		' Sign the document using BouncyCastle signer
		Dim pdfSignatureHandler = DigitalSignatureHandler.ForDocument(document, New PdfSharp.Snippets.Pdf.BouncyCastleSigner(GetCertificate(), PdfMessageDigestType.SHA256), options)

		' Save the signed document
		document.Save("PdfSharpSignature.pdf")
	End Sub

	Private Shared Function GetCertificate() As (X509Certificate2, X509Certificate2Collection)
		' Locate the certificate file and read its data
		Dim certFolder = "C:\Users\kyess\AppData\Roaming\Adobe\Acrobat\DC\Security"
		Dim pfxFile = Path.Combine(certFolder, "IronSoftware.pfx")
		Dim rawData = File.ReadAllBytes(pfxFile)

		' Load the certificate using its password (example password)
		Dim certificatePassword = "Passw0rd"
		Dim certificate = New X509Certificate2(rawData, certificatePassword, X509KeyStorageFlags.MachineKeySet Or X509KeyStorageFlags.PersistKeySet Or X509KeyStorageFlags.Exportable)

		' Create and return the certificate collection
		Dim collection = New X509Certificate2Collection()
		collection.Import(rawData, certificatePassword, X509KeyStorageFlags.MachineKeySet Or X509KeyStorageFlags.PersistKeySet Or X509KeyStorageFlags.Exportable)
		Return (certificate, collection)
	End Function
End Class
$vbLabelText   $csharpLabel

輸出

PDFsharp 以數位方式簽署 PDF 文件 vs IronPDF (程式碼範例):圖 2

如您在此所見,雖然它能夠建立數位簽章欄位,並將證書套用至我們的新文件,但與 IronPDF 之類的函式庫相比,這個過程是大量的、手動的,而且實作效率不高。

使用 IronPDF 添加數位簽章。

IronPDF 為開發人員提供 數位簽署 PDF 文件的簡潔方法。

using IronPdf;
using System.Security.Cryptography.X509Certificates;

public class Program
{
    static void Main(string[] args)
    {
        // Load the certificate with its password
        var sig = new PdfSignature("IronSoftware.pfx", "your-password");

        // Configure additional signature details
        sig.TimestampHashAlgorithm = TimestampHashAlgorithms.SHA256;
        sig.TimestampUrl = "http://timestamp.digicert.com";
        sig.SignatureImage = new PdfSignatureImage("IronPdf.png", 0, new Rectangle(150, 100, 200, 200));

        // Sign and save the PDF document
        sig.SignPdfFile("output.pdf");
    }
}
using IronPdf;
using System.Security.Cryptography.X509Certificates;

public class Program
{
    static void Main(string[] args)
    {
        // Load the certificate with its password
        var sig = new PdfSignature("IronSoftware.pfx", "your-password");

        // Configure additional signature details
        sig.TimestampHashAlgorithm = TimestampHashAlgorithms.SHA256;
        sig.TimestampUrl = "http://timestamp.digicert.com";
        sig.SignatureImage = new PdfSignatureImage("IronPdf.png", 0, new Rectangle(150, 100, 200, 200));

        // Sign and save the PDF document
        sig.SignPdfFile("output.pdf");
    }
}
Imports IronPdf
Imports System.Security.Cryptography.X509Certificates

Public Class Program
	Shared Sub Main(ByVal args() As String)
		' Load the certificate with its password
		Dim sig = New PdfSignature("IronSoftware.pfx", "your-password")

		' Configure additional signature details
		sig.TimestampHashAlgorithm = TimestampHashAlgorithms.SHA256
		sig.TimestampUrl = "http://timestamp.digicert.com"
		sig.SignatureImage = New PdfSignatureImage("IronPdf.png", 0, New Rectangle(150, 100, 200, 200))

		' Sign and save the PDF document
		sig.SignPdfFile("output.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

輸出

PDFsharp 以數位方式簽署 PDF 文件 vs IronPDF (程式碼範例):圖 3

本代碼示範如何使用 IronPDF 的 PdfSignature 類簽署 PDF 文件。 程式首先建立一個 PdfSignature 物件,指定 .pfx 證書檔案的位置及其密碼。 然後,它會設定額外的簽章屬性,例如雜湊演算法 (SHA256)、時間戳記 URL,以及簽章的自訂圖片 (IronPDF.png)。

最後,SignPdfFile 方法會被呼叫,將數位簽章套用至 PDF 文件,並將其儲存為 output.pdf。 此流程透過嵌入數位簽章以及時間戳記和視覺影像,確保 PDF 的完整性和真實性。

PDFSharp:

  • 以 MIT 授權開放原始碼。
  • 需要外部函式庫 (例如 BouncyCastle) 來提供數位簽章等進階功能。

IronPDF:

結論:IronPDF vs PDFsharp for Digital Signatures in C#.

在比較 IronPDFPDFsharp 用於在 C# 中為 PDF 新增 數位簽章時,這兩個函式庫都具有明顯的優勢,這取決於您的專案需求。

  • IronPDF是開發人員的理想選擇,無論是獨立的自由軟體開發人員,或是為公司工作的開發人員,都可以尋求簡單、易用的 API,將數位簽章套用至 PDF,並搭載現代化的功能。 其與數位簽章應用程式、HTML-to-PDF 轉換及其他 PDF 功能的無縫整合,使其成為以易用性和快速執行為優先考量的商業專案的最佳選擇。 IronPDF 提供付費支援和明確的商業授權結構,非常適合需要直接、可靠解決方案的企業。

  • PDFsharp 在基本的 PDF 創建和操作方面表現優異,但缺乏 IronPDF 所提供的進階功能和對數位簽章的直接支援。 雖然 PDFsharp 是開放原始碼且免費使用,但與 IronPDF 相比,其 API 在處理數位簽章時較不直覺,開發人員可能需要採用額外的解決方案或第三方函式庫來處理這些功能。

總而言之,IronPDF 是正在尋找簡單、快速的數位簽章及相關 PDF 任務解決方案的開發人員的最佳選擇,尤其是在商業環境中。 PDFsharp 更適合處理基本的 PDF 任務,但在數位簽章方面缺乏相同的易用性和功能集,因此更適合較簡單的專案或有額外自訂需求的專案。

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

常見問題解答

數位簽名如何確保 PDF 文件的真實性和完整性?

數位簽名使用加密技術來驗證 PDF 文件在簽署後是否未被更改。它們確認簽署者的身份並確保文件的內容保持不變,提供了安全性和法律效力。

使用 PDFsharp 添加數位簽名時,開發者可能面臨哪些挑戰?

使用 PDFsharp 添加數位簽名時,開發者通常需要整合像 BouncyCastle 這樣的第三方庫。這一要求可能會使實施過程變得複雜,因為開發者需要管理額外的依賴性來創建數字證書並簽署 PDF。

為什麼開發者可能會選擇商業 PDF 庫而不是開源的進行數位簽名?

商業 PDF 庫提供了高級功能、內建的數位簽名支持和使用者友好的 API。這些特性使其更適合尋求快速、可靠解決方案的開發者,尤其是在時間和效率至關重要的商業專案中。

如何在 .NET 應用程式中將 HTML 轉換成 PDF?

可以使用像 IronPDF 這樣的庫在 .NET 應用程式中將 HTML 轉換成 PDF,通過RenderHtmlAsPdf等方法直接將 HTML 字符串或檔案轉換為 PDF 文件,支持各種樣式和程式選項。

在商業專案中使用 IronPDF 處理 PDF 有哪些好處?

IronPDF 提供了一整套用於處理 PDF 的功能,包括數位簽名、HTML 到 PDF 轉換和表單處理。其強大的支持和使用者友好的 API 使其成為優先考慮高級功能和快速部署的商業專案的理想選擇。

可以使用 .NET 庫將時間戳添加到 PDF 數位簽名嗎?

是的,使用像 IronPDF 這樣的庫,可以在簽名配置中指定時間戳伺服器 URL 來將時間戳添加到 PDF 數位簽名中。此功能提高了簽署文件的可信度和法律合規性。

在選擇用於數位簽名實現的 PDF 庫時應考慮哪些因素?

選擇數位簽名的 PDF 庫時,考慮使用方便性、支持高級功能、與第三方工具的整合能力,以及專門的客戶支持的可用性,這些在像 IronPDF 這樣的商業庫中通常範圍更廣。

Curtis Chau
技術作家

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

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

鋼鐵支援團隊

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