C# 開發人員的 PDF簽名 完整指南:使用 IronPDF 數位簽章
本綜合指南向 C# 開發人員展示了如何使用 IronPDF 對 PDF 進行數位簽名,內容涵蓋了基於證書的簽名、視覺戳記和互動表單欄位,以確保文檔的真實性和安全性。
在許多應用程式中,向 PDF 文件添加簽名是一項常見要求,但"簽名"的含義可能有所不同。 對某些人來說,關鍵在於使用安全憑證應用防篡改的數位簽章。 對於其他人來說,這可能是在文件上蓋上手寫簽名圖像,或者添加一個互動式表單欄位供使用者進行電子簽名。
本指南為 C# 開發人員提供了使用IronPDF 適用於 .NET 程式庫完成所有這些任務的全面演練。 我們將涵蓋從應用安全的 X509Certificate2 數位簽章到新增圖形簽章和建立互動式簽章網域的所有內容,確保您的 PDF 文件真實、安全且專業。
快速入門:使用IronPDF輕鬆對 PDF 進行數位簽章
使用 IronPDF,透過簡單直接的流程,即可快速開始對 PDF 文件進行數位簽章。 本範例示範如何使用 .pfx 憑證對 PDF 檔案進行驗證和簽名,以確保文件的完整性和真實性。 請遵循以下步驟,將數位簽章無縫整合至您的應用程式。
最小工作流程(5 個步驟)
- 安裝適用於 .NET 的 IronPDF 庫。
- Apply a digital signature using an `X509Certificate2` object.
- 添加圖像以表示數位簽名。
- 在 PDF 檔案上新增圖形或手寫簽名。
- 新增用於電子簽名的互動式簽名表單欄位。
如何將數位簽章應用於具有憑證的 PDF 檔案?
您可以使用數位憑證檔案(例如 .pfx 或 .p12)對 PDF 文件套用數位簽名,以確保文件的真實性和完整性。 此流程確保文件自簽署以來未被篡改。 如需完整瞭解數位簽章功能,請瀏覽我們的 全面數位簽章指南。
IronPDF 為此提供了一個簡單的 API,支援多種應用數位簽章的方式。 此功能的核心是 PdfSignature 類,它封裝了憑證和簽署的所有相關元資料。
| 簽名方法 | 描述 |
|---|---|
| `Sign` | 使用您建立和配置的**`PdfSignature`物件**對 PDF 進行簽署。 |
| `SignWithFile | 使用位於磁碟上的數位簽章憑證檔案( `.pfx`或`.p12` )對 PDF 進行簽署。 |
| `SignWithStore | 使用電腦憑證儲存區中的數位簽名對 PDF 檔案進行簽名,該數位簽名透過其**指紋 ID**進行識別。 |
使用 X509Certificate2 對象
為了實現最大程度的控制,您可以從憑證檔案建立 X509Certificate2 物件。 IronPDF 完全符合 X509Certificate2 標準,為數位簽章實作提供了強大且安全的方法。 建立憑證物件時,請確保將 X509KeyStorageFlags 設定為 Exportable,因為底層加密 API 要求這樣做。您可以在我們的程式碼庫中查看數位簽名的實際範例。
Install-Package IronPdf
using IronPdf;
using IronPdf.Signing;
using System.Security.Cryptography.X509Certificates;
// Create a new PDF from an HTML string for demonstration.
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Signed Document</h1><p>This document has been digitally signed.</p>");
// Load the certificate from a .pfx file with its password.
// The X509KeyStorageFlags.Exportable flag is crucial for allowing the private key to be used in the signing process.
var cert = new X509Certificate2("IronSoftware.pfx", "123456", X509KeyStorageFlags.Exportable);
// Create a PdfSignature object using the loaded certificate.
var signature = new PdfSignature(cert);
// Apply the signature to the PDF document.
pdf.Sign(signature);
// Save the securely signed PDF document.
pdf.SaveAs("Signed.pdf");
using IronPdf;
using IronPdf.Signing;
using System.Security.Cryptography.X509Certificates;
// Create a new PDF from an HTML string for demonstration.
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Signed Document</h1><p>This document has been digitally signed.</p>");
// Load the certificate from a .pfx file with its password.
// The X509KeyStorageFlags.Exportable flag is crucial for allowing the private key to be used in the signing process.
var cert = new X509Certificate2("IronSoftware.pfx", "123456", X509KeyStorageFlags.Exportable);
// Create a PdfSignature object using the loaded certificate.
var signature = new PdfSignature(cert);
// Apply the signature to the PDF document.
pdf.Sign(signature);
// Save the securely signed PDF document.
pdf.SaveAs("Signed.pdf");
Imports IronPdf
Imports IronPdf.Signing
Imports System.Security.Cryptography.X509Certificates
' Create a new PDF from an HTML string for demonstration.
Private renderer = New ChromePdfRenderer()
Private pdf = renderer.RenderHtmlAsPdf("<h1>Signed Document</h1><p>This document has been digitally signed.</p>")
' Load the certificate from a .pfx file with its password.
' The X509KeyStorageFlags.Exportable flag is crucial for allowing the private key to be used in the signing process.
Private cert = New X509Certificate2("IronSoftware.pfx", "123456", X509KeyStorageFlags.Exportable)
' Create a PdfSignature object using the loaded certificate.
Private signature = New PdfSignature(cert)
' Apply the signature to the PDF document.
pdf.Sign(signature)
' Save the securely signed PDF document.
pdf.SaveAs("Signed.pdf")
上面的程式碼首先產生一個簡單的PDF檔案。 然後,它將 .pfx 憑證檔案載入到 X509Certificate2 物件中。 此物件代表數位身份,並傳遞給 PdfSignature 建構函數。 最後,pdf.Sign 方法在儲存文件之前將此簽章套用至文件。 For more information on the X509Certificate2 class, you can refer to the official Microsoft documentation.
為數位簽名添加詳細信息
數位簽章可以包含憑證以外的內容; 您可以嵌入豐富的元數據,以提供有關簽名的上下文資訊。 這包括簽署地點、原因、聯絡資訊以及來自可信任機構的安全時間戳。 您也可以設定和編輯元資料,以取得額外的文件屬性。
添加這些細節可以改進文件的審計跟踪,並為核實人員提供有價值的資訊。 IronPDF也支援使用現代 SHA256 和 SHA512 雜湊演算法的時間戳伺服器。
using IronPdf;
using IronPdf.Signing;
using IronSoftware.Drawing;
using System;
// Load an existing PDF document to be signed.
var pdf = PdfDocument.FromFile("invoice.pdf");
// Create a PdfSignature object directly from the certificate file and password.
var signature = new PdfSignature("IronSoftware.pfx", "123456");
// Add detailed metadata to the signature for a comprehensive audit trail.
// These properties enhance the signature's credibility and provide context
signature.SignatureDate = DateTime.Now;
signature.SigningContact = "legal@ironsoftware.com";
signature.SigningLocation = "Chicago, USA";
signature.SigningReason = "Contractual Agreement";
// Add a secure timestamp from a trusted Time Stamp Authority (TSA).
// This provides cryptographic proof of the signing time.
signature.TimeStampUrl = new Uri("[http://timestamp.digicert.com](http://timestamp.digicert.com)");
signature.TimestampHashAlgorithm = TimestampHashAlgorithms.SHA256;
// Apply a visual appearance to the signature. (More on this in the next section)
signature.SignatureImage = new PdfSignatureImage("assets/visual-signature.png", 0, new Rectangle(350, 750, 200, 100));
// Sign the PDF document with the configured signature object.
pdf.Sign(signature);
// Save the final, signed PDF document.
pdf.SaveAs("DetailedSignature.pdf");
using IronPdf;
using IronPdf.Signing;
using IronSoftware.Drawing;
using System;
// Load an existing PDF document to be signed.
var pdf = PdfDocument.FromFile("invoice.pdf");
// Create a PdfSignature object directly from the certificate file and password.
var signature = new PdfSignature("IronSoftware.pfx", "123456");
// Add detailed metadata to the signature for a comprehensive audit trail.
// These properties enhance the signature's credibility and provide context
signature.SignatureDate = DateTime.Now;
signature.SigningContact = "legal@ironsoftware.com";
signature.SigningLocation = "Chicago, USA";
signature.SigningReason = "Contractual Agreement";
// Add a secure timestamp from a trusted Time Stamp Authority (TSA).
// This provides cryptographic proof of the signing time.
signature.TimeStampUrl = new Uri("[http://timestamp.digicert.com](http://timestamp.digicert.com)");
signature.TimestampHashAlgorithm = TimestampHashAlgorithms.SHA256;
// Apply a visual appearance to the signature. (More on this in the next section)
signature.SignatureImage = new PdfSignatureImage("assets/visual-signature.png", 0, new Rectangle(350, 750, 200, 100));
// Sign the PDF document with the configured signature object.
pdf.Sign(signature);
// Save the final, signed PDF document.
pdf.SaveAs("DetailedSignature.pdf");
Imports IronPdf
Imports IronPdf.Signing
Imports IronSoftware.Drawing
Imports System
' Load an existing PDF document to be signed.
Dim pdf = PdfDocument.FromFile("invoice.pdf")
' Create a PdfSignature object directly from the certificate file and password.
Dim signature = New PdfSignature("IronSoftware.pfx", "123456")
' Add detailed metadata to the signature for a comprehensive audit trail.
' These properties enhance the signature's credibility and provide context
signature.SignatureDate = DateTime.Now
signature.SigningContact = "legal@ironsoftware.com"
signature.SigningLocation = "Chicago, USA"
signature.SigningReason = "Contractual Agreement"
' Add a secure timestamp from a trusted Time Stamp Authority (TSA).
' This provides cryptographic proof of the signing time.
signature.TimeStampUrl = New Uri("http://timestamp.digicert.com")
signature.TimestampHashAlgorithm = TimestampHashAlgorithms.SHA256
' Apply a visual appearance to the signature. (More on this in the next section)
signature.SignatureImage = New PdfSignatureImage("assets/visual-signature.png", 0, New Rectangle(350, 750, 200, 100))
' Sign the PDF document with the configured signature object.
pdf.Sign(signature)
' Save the final, signed PDF document.
pdf.SaveAs("DetailedSignature.pdf")
如果簽章憑證不在系統的受信任儲存區中,您可能會在某些 PDF 檢視器中看到警告圖示。 要獲得綠色對勾,必須將憑證新增至查看者的受信任身分。
如何為數位簽章添加視覺元素?
雖然數位簽章已透過加密技術嵌入 PDF 文件中,但在頁面上顯示其視覺表示通常很有用。 這可以是公司標誌、手寫簽名圖片或其他圖形。 IronPDF可以輕鬆地將影像新增至 PdfSignature 物件中。
您可以從文件或流中載入圖像,並將其精確地放置在 PDF 的任何頁面上。 支援的影像格式包括 PNG、JPEG、GIF、BMP、TIFF 和 WebP。此技術與您在 PDF 文件上標示文字和影像的方式類似。
using IronPdf.Signing;
using IronSoftware.Drawing;
// This example demonstrates various ways to add a visual image to a PDF signature.
// Create a PdfSignature object.
var signature = new PdfSignature("IronSoftware.pfx", "123456");
// Define the position and size for the signature image on the first page (index 0).
// Rectangle parameters: x position, y position, width, height
var signatureRectangle = new Rectangle(350, 750, 200, 100);
// Option 1: Set the SignatureImage property directly.
// This is the most straightforward approach
signature.SignatureImage = new PdfSignatureImage("assets/visual-signature.png", 0, signatureRectangle);
// Option 2: Use the LoadSignatureImageFromFile method.
// This method provides the same functionality with a different syntax
signature.LoadSignatureImageFromFile("assets/visual-signature.png", 0, signatureRectangle);
// Option 3: Load an image from a stream. This is useful for images generated in memory.
// Perfect for scenarios where images are retrieved from databases or web services
AnyBitmap image = AnyBitmap.FromFile("assets/visual-signature.png");
using (var imageStream = image.ToStream())
{
signature.LoadSignatureImageFromStream(imageStream, 0, signatureRectangle);
}
// After configuring the signature image, apply it to a PDF.
var pdf = PdfDocument.FromFile("invoice.pdf");
pdf.Sign(signature);
pdf.SaveAs("VisualSignature.pdf");
using IronPdf.Signing;
using IronSoftware.Drawing;
// This example demonstrates various ways to add a visual image to a PDF signature.
// Create a PdfSignature object.
var signature = new PdfSignature("IronSoftware.pfx", "123456");
// Define the position and size for the signature image on the first page (index 0).
// Rectangle parameters: x position, y position, width, height
var signatureRectangle = new Rectangle(350, 750, 200, 100);
// Option 1: Set the SignatureImage property directly.
// This is the most straightforward approach
signature.SignatureImage = new PdfSignatureImage("assets/visual-signature.png", 0, signatureRectangle);
// Option 2: Use the LoadSignatureImageFromFile method.
// This method provides the same functionality with a different syntax
signature.LoadSignatureImageFromFile("assets/visual-signature.png", 0, signatureRectangle);
// Option 3: Load an image from a stream. This is useful for images generated in memory.
// Perfect for scenarios where images are retrieved from databases or web services
AnyBitmap image = AnyBitmap.FromFile("assets/visual-signature.png");
using (var imageStream = image.ToStream())
{
signature.LoadSignatureImageFromStream(imageStream, 0, signatureRectangle);
}
// After configuring the signature image, apply it to a PDF.
var pdf = PdfDocument.FromFile("invoice.pdf");
pdf.Sign(signature);
pdf.SaveAs("VisualSignature.pdf");
Imports IronPdf.Signing
Imports IronSoftware.Drawing
' This example demonstrates various ways to add a visual image to a PDF signature.
' Create a PdfSignature object.
Dim signature As New PdfSignature("IronSoftware.pfx", "123456")
' Define the position and size for the signature image on the first page (index 0).
' Rectangle parameters: x position, y position, width, height
Dim signatureRectangle As New Rectangle(350, 750, 200, 100)
' Option 1: Set the SignatureImage property directly.
' This is the most straightforward approach
signature.SignatureImage = New PdfSignatureImage("assets/visual-signature.png", 0, signatureRectangle)
' Option 2: Use the LoadSignatureImageFromFile method.
' This method provides the same functionality with a different syntax
signature.LoadSignatureImageFromFile("assets/visual-signature.png", 0, signatureRectangle)
' Option 3: Load an image from a stream. This is useful for images generated in memory.
' Perfect for scenarios where images are retrieved from databases or web services
Dim image As AnyBitmap = AnyBitmap.FromFile("assets/visual-signature.png")
Using imageStream = image.ToStream()
signature.LoadSignatureImageFromStream(imageStream, 0, signatureRectangle)
End Using
' After configuring the signature image, apply it to a PDF.
Dim pdf As PdfDocument = PdfDocument.FromFile("invoice.pdf")
pdf.Sign(signature)
pdf.SaveAs("VisualSignature.pdf")
這段程式碼展示了三種向數位簽名添加視覺組件的等效方法。 無論影像儲存在磁碟還是記憶體中,您都可以在簽名過程中輕鬆地將其添加到 PDF 檔案中。 這彌合了無形的加密安全性和可見的文件審批之間的差距。
簽名後如何控製文件權限?
簽署文件時,您可能需要明確規定之後允許進行哪些更改(如果有的話)。 例如,您可能希望完全鎖定文檔,或只允許使用者填寫表單欄位。 IronPDF可讓您使用 SignaturePermissions 枚舉設定這些權限。 如需更進階的權限控制,請參閱我們的 設定 PDF 密碼和權限指南。
設定簽名權限是管理文件生命週期的關鍵環節。 它確保在您簽署後,文件的完整性能夠按照您的規定得到維護。 如果使用者執行了不允許的操作,則簽名將失效。
| `SignaturePermissions`成員 | 定義 |
|---|---|
| `NoChangesAllowed` | 不允許進行任何形式的更改。該文件已被鎖定。 |
| `FormFillingAllowed` | 僅允許填寫現有表單欄位和簽名。 |
| `AnnotationsAndFormFillingAllowed` | 允許填寫表單、簽名以及建立或修改註釋。 |
儲存並簽署特定 PDF 版本
PDF 檔案可以儲存變更歷史記錄,就像版本控制系統一樣。 這稱為增量儲蓄。 當你簽署PDF文件時,該簽名僅適用於該文件的特定版本。 對於文件需要經過多個審批階段的工作流程來說,這一點至關重要。 請閱讀我們的詳細指南,以了解更多關於管理PDF修訂歷史記錄的資訊。
在以下範例中,我們載入一個 PDF 文件,進行編輯,然後簽署目前版本,同時只允許填寫表單作為未來的變更。 我們使用 SaveAsRevision 在儲存文件之前將目前狀態提交到文件的歷史記錄中。
using IronPdf.Signing;
// Load a PDF file with change tracking enabled.
// This enables incremental save functionality for revision management
var pdf = PdfDocument.FromFile("annual_census.pdf", ChangeTrackingModes.EnableChangeTracking);
// Placeholder for edits: You might add text, fill forms, or add annotations here.
// For example: pdf.Annotations.Add(new TextAnnotation(...));
// Or: pdf.Form["fieldName"].Value = "New Value";
// Sign the current state of the document using SignWithFile for convenience.
// We set permissions to allow further signatures and form filling.
pdf.SignWithFile(
"assets/IronSignature.p12",
"password",
SignaturePermissions.AdditionalSignaturesAndFormFillingAllowed);
// Save the current state as a distinct revision within the PDF's history.
// This creates a snapshot that can be referenced later
PdfDocument pdfWithRevision = pdf.SaveAsRevision();
// Save the final PDF with its full revision history to a new file.
pdfWithRevision.SaveAs("annual_census_signed.pdf");
using IronPdf.Signing;
// Load a PDF file with change tracking enabled.
// This enables incremental save functionality for revision management
var pdf = PdfDocument.FromFile("annual_census.pdf", ChangeTrackingModes.EnableChangeTracking);
// Placeholder for edits: You might add text, fill forms, or add annotations here.
// For example: pdf.Annotations.Add(new TextAnnotation(...));
// Or: pdf.Form["fieldName"].Value = "New Value";
// Sign the current state of the document using SignWithFile for convenience.
// We set permissions to allow further signatures and form filling.
pdf.SignWithFile(
"assets/IronSignature.p12",
"password",
SignaturePermissions.AdditionalSignaturesAndFormFillingAllowed);
// Save the current state as a distinct revision within the PDF's history.
// This creates a snapshot that can be referenced later
PdfDocument pdfWithRevision = pdf.SaveAsRevision();
// Save the final PDF with its full revision history to a new file.
pdfWithRevision.SaveAs("annual_census_signed.pdf");
Imports IronPdf.Signing
' Load a PDF file with change tracking enabled.
' This enables incremental save functionality for revision management
Dim pdf = PdfDocument.FromFile("annual_census.pdf", ChangeTrackingModes.EnableChangeTracking)
' Placeholder for edits: You might add text, fill forms, or add annotations here.
' For example: pdf.Annotations.Add(New TextAnnotation(...))
' Or: pdf.Form("fieldName").Value = "New Value"
' Sign the current state of the document using SignWithFile for convenience.
' We set permissions to allow further signatures and form filling.
pdf.SignWithFile(
"assets/IronSignature.p12",
"password",
SignaturePermissions.AdditionalSignaturesAndFormFillingAllowed)
' Save the current state as a distinct revision within the PDF's history.
' This creates a snapshot that can be referenced later
Dim pdfWithRevision As PdfDocument = pdf.SaveAsRevision()
' Save the final PDF with its full revision history to a new file.
pdfWithRevision.SaveAs("annual_census_signed.pdf")
理解增量保存是進階 PDF 工作流程的關鍵。 雖然簡單的檢視器可能只會顯示最新版本,但像 Adobe Acrobat 這樣的工具可以顯示完整的修訂歷史記錄,顯示誰簽署了哪個版本以及簽名之間做了哪些更改。 IronPDF讓您可以完全透過程式控制此流程。
對於管理複雜文件工作流程且需要高度安全性和合規性的企業而言,可能需要一個全面的解決方案。 Iron Software提供Iron Suite ,其中包括用於簽名和操作的IronPDF ,以及其他用於各種文件處理任務的庫,只需一次性付款即可獲得。
如何管理和驗證不同版本中的簽名?
PDF 文件可以在其各個版本中使用多個簽章。 IronPDF提供了有效管理此歷史記錄的工具。
-回滾到先前的版本:您可以使用 GetRevision 方法將文件還原到先前的狀態。 這將丟棄該版本之後所做的所有更改和簽名。
-驗證所有簽章:VerifySignatures 方法檢查文件所有版本中所有簽章的有效性。 只有當所有簽名都有效且沒有進行任何未經授權的更改時,才會返回 true。
-刪除簽名:RemoveSignatures 方法將從文件的每個版本中剝離所有數位簽名,創建一個乾淨的、未簽名的版本。
// Load a PDF with a complex signature history.
var pdf = PdfDocument.FromFile("multi_signed_report.pdf");
// Verify all signatures across all revisions.
// This ensures document integrity throughout its entire history
bool allSignaturesValid = pdf.VerifySignatures();
Console.WriteLine($"All signatures are valid: {allSignaturesValid}");
// Roll back to the first revision (index 0).
// Useful for reviewing the original document state
if (pdf.RevisionCount > 1)
{
PdfDocument firstRevision = pdf.GetRevision(0);
firstRevision.SaveAs("report_first_revision.pdf");
}
// Create a completely unsigned version of the document.
// This removes all digital signatures while preserving content
pdf.RemoveSignatures();
pdf.SaveAs("report_unsigned.pdf");
// Load a PDF with a complex signature history.
var pdf = PdfDocument.FromFile("multi_signed_report.pdf");
// Verify all signatures across all revisions.
// This ensures document integrity throughout its entire history
bool allSignaturesValid = pdf.VerifySignatures();
Console.WriteLine($"All signatures are valid: {allSignaturesValid}");
// Roll back to the first revision (index 0).
// Useful for reviewing the original document state
if (pdf.RevisionCount > 1)
{
PdfDocument firstRevision = pdf.GetRevision(0);
firstRevision.SaveAs("report_first_revision.pdf");
}
// Create a completely unsigned version of the document.
// This removes all digital signatures while preserving content
pdf.RemoveSignatures();
pdf.SaveAs("report_unsigned.pdf");
Imports System
' Load a PDF with a complex signature history.
Dim pdf = PdfDocument.FromFile("multi_signed_report.pdf")
' Verify all signatures across all revisions.
' This ensures document integrity throughout its entire history
Dim allSignaturesValid As Boolean = pdf.VerifySignatures()
Console.WriteLine($"All signatures are valid: {allSignaturesValid}")
' Roll back to the first revision (index 0).
' Useful for reviewing the original document state
If pdf.RevisionCount > 1 Then
Dim firstRevision As PdfDocument = pdf.GetRevision(0)
firstRevision.SaveAs("report_first_revision.pdf")
End If
' Create a completely unsigned version of the document.
' This removes all digital signatures while preserving content
pdf.RemoveSignatures()
pdf.SaveAs("report_unsigned.pdf")
如何在PDF文件上新增手寫簽名?
有時,您不需要數位簽名的加密安全性,而只是想套用視覺電子簽名,例如掃描的手寫簽名。 這通常被稱為蓋章。 IronPDF可以使用其 Watermark 或 Stamp 功能來實現這一點。 如需了解更多進階浮水印選項,請瀏覽我們的自訂浮水印指南。
讓我們從一個範例發票 PDF 和一個手寫簽名的圖片開始。
蓋章前的原始發票PDF文件。
以下是我們將要使用的標誌性圖像:
手寫簽名範例圖片。
以下程式碼使用 Watermark 屬性將此圖像印在 PDF 的右下角。
using IronPdf.Editing;
// Load the existing PDF document.
var pdf = PdfDocument.FromFile("invoice.pdf");
// Create an HtmlStamp containing our signature image.
// HtmlStamp allows us to position HTML content precisely on the page
var signatureStamp = new HtmlStamp("<img src='assets/signature.png'/>")
{
// Configure the stamp's position and appearance.
VerticalAlignment = VerticalAlignment.Bottom,
HorizontalAlignment = HorizontalAlignment.Right,
Margin = 10, // Add some space from the edge.
Opacity = 90 // Make it slightly transparent for a more authentic look.
};
// Apply the stamp to all pages of the PDF.
// You can also specify specific page numbers if needed
pdf.ApplyStamp(signatureStamp);
// Save the modified PDF document.
pdf.SaveAs("official_invoice.pdf");
using IronPdf.Editing;
// Load the existing PDF document.
var pdf = PdfDocument.FromFile("invoice.pdf");
// Create an HtmlStamp containing our signature image.
// HtmlStamp allows us to position HTML content precisely on the page
var signatureStamp = new HtmlStamp("<img src='assets/signature.png'/>")
{
// Configure the stamp's position and appearance.
VerticalAlignment = VerticalAlignment.Bottom,
HorizontalAlignment = HorizontalAlignment.Right,
Margin = 10, // Add some space from the edge.
Opacity = 90 // Make it slightly transparent for a more authentic look.
};
// Apply the stamp to all pages of the PDF.
// You can also specify specific page numbers if needed
pdf.ApplyStamp(signatureStamp);
// Save the modified PDF document.
pdf.SaveAs("official_invoice.pdf");
Imports IronPdf.Editing
' Load the existing PDF document.
Dim pdf = PdfDocument.FromFile("invoice.pdf")
' Create an HtmlStamp containing our signature image.
' HtmlStamp allows us to position HTML content precisely on the page
Dim signatureStamp = New HtmlStamp("<img src='assets/signature.png'/>") With {
' Configure the stamp's position and appearance.
.VerticalAlignment = VerticalAlignment.Bottom,
.HorizontalAlignment = HorizontalAlignment.Right,
.Margin = 10, ' Add some space from the edge.
.Opacity = 90 ' Make it slightly transparent for a more authentic look.
}
' Apply the stamp to all pages of the PDF.
' You can also specify specific page numbers if needed
pdf.ApplyStamp(signatureStamp)
' Save the modified PDF document.
pdf.SaveAs("official_invoice.pdf")
加蓋印章後的 PDF 結果是什麼樣子的?
程式碼運行後,簽名圖像會被印在文件上,從而產生一張帶有視覺簽名的發票。
最終的PDF檔案右下角蓋有手寫簽名印章。
如何在PDF中加入互動式簽名域?
對於需要在 Adobe Acrobat 等 PDF 檢視器中由最終使用者簽署的文檔,您可以新增互動式簽名表單欄位。 這將建立一個空白的、可點擊的區域,提示使用者套用自己的數位簽章。 有關 PDF 表單的完整指南,請參閱我們的PDF 表單建立教學。
您可以建立一個 SignatureFormField 並將其新增至 PDF 的表單集合中。 您可以精確控制它在頁面上的位置和大小。 這對於需要多人簽署的文件,或者當您需要從外部人員收集簽名時,尤其有用。
using IronPdf.Forms;
using IronSoftware.Drawing;
// Create a new PDF to add the signature field to.
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Please Sign Below</h1>");
// Define the properties for the signature form field.
string fieldName = "ClientSignature"; // Unique identifier for the field
int pageIndex = 0; // Add to the first page (zero-indexed)
var fieldRect = new Rectangle(50, 200, 300, 100); // Position: (x, y), Size: (width, height)
// Create the SignatureFormField object.
// This creates an interactive field that users can click to sign
var signatureField = new SignatureFormField(fieldName, pageIndex, fieldRect);
// Add the signature field to the PDF's form.
pdf.Form.Add(signatureField);
// Save the PDF with the new interactive signature field.
pdf.SaveAs("interactive_signature.pdf");
using IronPdf.Forms;
using IronSoftware.Drawing;
// Create a new PDF to add the signature field to.
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Please Sign Below</h1>");
// Define the properties for the signature form field.
string fieldName = "ClientSignature"; // Unique identifier for the field
int pageIndex = 0; // Add to the first page (zero-indexed)
var fieldRect = new Rectangle(50, 200, 300, 100); // Position: (x, y), Size: (width, height)
// Create the SignatureFormField object.
// This creates an interactive field that users can click to sign
var signatureField = new SignatureFormField(fieldName, pageIndex, fieldRect);
// Add the signature field to the PDF's form.
pdf.Form.Add(signatureField);
// Save the PDF with the new interactive signature field.
pdf.SaveAs("interactive_signature.pdf");
Imports IronPdf.Forms
Imports IronSoftware.Drawing
' Create a new PDF to add the signature field to.
Dim renderer As New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf("<h1>Please Sign Below</h1>")
' Define the properties for the signature form field.
Dim fieldName As String = "ClientSignature" ' Unique identifier for the field
Dim pageIndex As Integer = 0 ' Add to the first page (zero-indexed)
Dim fieldRect As New Rectangle(50, 200, 300, 100) ' Position: (x, y), Size: (width, height)
' Create the SignatureFormField object.
' This creates an interactive field that users can click to sign
Dim signatureField As New SignatureFormField(fieldName, pageIndex, fieldRect)
' Add the signature field to the PDF's form.
pdf.Form.Add(signatureField)
' Save the PDF with the new interactive signature field.
pdf.SaveAs("interactive_signature.pdf")
當使用者打開此 PDF 文件時,他們會看到一個可點擊的字段,允許他們使用自己的數位 ID 完成簽名過程。 您可以參考我們的PDF 表單建立指南,以了解更多關於建立和管理互動式表單的資訊。
透過程式設計方式新增至 PDF 文件中的未簽章互動式簽章網域。
如何從已驗證的簽章中檢索簽章人姓名?
要取得簽署簽署的憑證擁有者的通用名稱,我們可以使用 VerifiedSignature 類別來存取 SignerName 屬性。 下面的程式碼片段示範如何實現這一點。
:path=/static-assets/pdf/content-code-examples/how-to/signing-find-signer-name.cs
using IronPdf;
using System;
// Import the Signed PDF report
var pdf = PdfDocument.FromFile("multi_signed_report.pdf");
// Using GetVerifiedSignatures() obtain a list of `VerifiedSignature` objects from the PDF
pdf.GetVerifiedSignatures().ForEach(signature =>
{
// Print out the SignerName of each `VerifiedSignature` object
Console.WriteLine($"SignatureName: {signature.SignerName}");
});
Imports IronPdf
Imports System
' Import the Signed PDF report
Dim pdf = PdfDocument.FromFile("multi_signed_report.pdf")
' Using GetVerifiedSignatures() obtain a list of `VerifiedSignature` objects from the PDF
pdf.GetVerifiedSignatures().ForEach(Sub(signature)
' Print out the SignerName of each `VerifiedSignature` object
Console.WriteLine($"SignatureName: {signature.SignerName}")
End Sub)
導入簽署的 PDF 文件後,我們利用 GetVerifiedSignatures 方法檢索報告中的 VerifiedSignature 物件列表,並為每個簽名列印 SignerName。
請注意,此值是從憑證的主題可分辨名稱 (SubjectDN) 中提取的,如果 CN 欄位不存在,則將傳回 null。
使用IronPDF進行 PDF 簽名的下一步是什麼?
本指南示範了IronPDF強大且靈活的 PDF 簽名功能。 無論您需要應用具有詳細元資料的安全數位簽名、管理文件修訂、新增視覺簽名,還是建立互動式表單, IronPDF提供了一個全面且對開發者友好的 API 來完成這項工作。
要繼續探索,您可以下載IronPDF .NET庫,並獲得免費試用許可證,以便在您的專案中測試其所有功能。 如需了解更高級的文件操作技巧,包括新增註解和使用表單字段,請查看我們豐富的文件和教學課程。
準備好看看您還能做些什麼嗎? 請造訪我們的教學頁面:簽署和保護 PDF 文件
常見問題解答
如何在 C# 中使用憑證對 PDF 進行數位簽章?
使用 IronPDF,您只需使用 PdfSignature 類一行代碼即可對 PDF 進行數位簽名。只需用您的證書文件(.pfx 或 .p12)和密碼創建一個新的 PdfSignature 物件,然後調用 SignPdfFile() 方法。例如:new IronPDF.Signing.PdfSignature("certificate.pfx", "password").SignPdfFile("input.pdf")。這將使用您的 X509Certificate2 套用防篡改數位簽章,以確保文件的真實性。
支援哪些類型的 PDF 簽名?
IronPDF 支持三种主要的 PDF 签名类型:1) 使用 X509Certificate2 憑證進行驗證和防篡改的數位簽章;2) 在文件中添加圖形或手寫簽名圖像的視覺簽章;以及 3) 允許用戶對 PDF 進行電子簽名的互動簽名表單欄位。每種類型對於文件安全性和工作流程需求都有不同的用途。
哪些憑證格式可用於數位簽章?
IronPDF 支援常見的數位憑證格式,包括 .pfx(個人資訊交換)和 .p12 檔案。這些證書檔案包含數位簽章所需的公開金鑰和私人金鑰。IronPDF 中的 PdfSignature 類別可以與任何 X509Certificate2 物件一起工作,為您加載和管理簽名證書提供了靈活性。
我可以在數位簽章中加入視覺表示嗎?
是的,IronPDF 允許您在數位簽名中加入視覺元素。您可以在加密簽章旁加入圖形表示,例如手寫簽章圖像、公司標誌或自訂印章。這將數位憑證的安全性與視覺確認結合起來,使簽署的文件既安全又具有專業性。
如何建立互動式簽名欄位供使用者進行電子簽名?
IronPDF 可讓您在 PDF 文件中加入互動式簽名表單欄位。這些欄位允許使用者透過點擊並繪製簽名或上傳簽名影像,以電子方式簽署文件。此功能非常適合建立需要收集簽名的文件,例如需要多方簽名的合約或表格。
簽署 PDF 是否能確保文件的完整性?
是的,當您使用 IronPDF 以 X509Certificate2 對 PDF 進行數位簽章時,會建立一個防篡改的封印,以確保文件的完整性。數位簽章保證文件自簽署後未被修改。簽名後對 PDF 的任何修改都會使簽名失效,提醒收件人該文件可能已被洩露。

