天天看點

C# 給PDF簽名時添加時間戳的2種方法(附VB.NET代碼)

在PDF添加簽名時,支援添加可信時間戳來保證文檔的法律效應。本文,将通過C#程式代碼介紹如何添加可信時間戳,可通過2種方法來實作。文中附上VB.NET代碼,有需可供參考。

一、程式運作環境

  • 編譯環境:Visual Studio/.NetFramework 4.8
  • 所需測試檔案:PDF、.pfx數字證書及秘鑰、PDF類庫(Spire.PDF for  .NET )
  • 可信時間戳伺服器:URL位址

注:VS程式中,在“解決方案資料總管中”先引用spire.pdf.dll檔案,如下圖,

C# 給PDF簽名時添加時間戳的2種方法(附VB.NET代碼)

這裡可以通過Nuget下載下傳該檔案。或者在手動下載下傳引用,dll檔案在下載下傳後的檔案包BIN檔案夾下,如本次測試使用的是.NET4.0下面的dll,即spire.pdf_7.5.7\BIN\NET4.0\Spire.Pdf.dll,如圖:

C# 給PDF簽名時添加時間戳的2種方法(附VB.NET代碼)

二、程式代碼

添加簽名時,這裡可分别通過兩個類來實作,即PdfSignature 和 PdfOrdinarySignatureMaker類。下面分别以兩個代碼示例展示如何簽名并添加時間戳。

1. 通過PdfSignature類來簽名,添加時間戳

C#

using Spire.Pdf;
using Spire.Pdf.Security;
using System.Drawing;

namespace TimeStamp
{
    class Program
    {
        static void Main(string[] args)
        {
            //加載PDF文檔
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile("sample.pdf");

            //擷取第2頁
            PdfPageBase page = pdf.Pages[1];

            //加載數字證書(.pfx檔案及秘鑰)
            PdfCertificate cert = new PdfCertificate("test.pfx", "123456");

            //加載簽名圖檔
            Spire.Pdf.Graphics.PdfImage image = Spire.Pdf.Graphics.PdfImage.FromFile("sign.png");

            //添加與圖檔大小相同的簽名到第2頁指定坐标位置
            PdfSignature signature = new PdfSignature(page.Document, page, cert, "sign1");//添加數字簽名
            signature.Bounds = new RectangleF(new PointF(400,700), new SizeF(image.Width, image.Height));//設定簽名的頁面坐标位置、大小與圖檔相同
            signature.SignImageSource = image;
            signature.GraphicsMode = Spire.Pdf.Security.GraphicMode.SignImageAndSignDetail;//設定簽名為圖檔模式
            signature.SignImageLayout = Spire.Pdf.Security.SignImageLayout.Stretch;
            signature.DocumentPermissions = Spire.Pdf.Security.PdfCertificationFlags.AllowFormFill | Spire.Pdf.Security.PdfCertificationFlags.AllowComments;//文檔權限           

            //配置時間戳伺服器,添加時間戳
            string url = "Your TimeStamp Server URL";
            signature.ConfigureTimestamp(url);
            //signature.ConfigureTimestamp(url, "Author", "123654");//添加時間戳時設定使用者名和密碼
            

            //儲存文檔
            pdf.SaveToFile("TimeStamp1.pdf",FileFormat.PDF);
            System.Diagnostics.Process.Start("TimeStamp1.pdf");
        }
    }
}      

VB.NET

Imports Spire.Pdf
Imports Spire.Pdf.Security
Imports System.Drawing

Namespace TimeStamp
    Class Program
        Private Shared Sub Main(args As String())
            '加載PDF文檔
            Dim pdf As New PdfDocument()
            pdf.LoadFromFile("sample.pdf")

            '擷取第2頁
            Dim page As PdfPageBase = pdf.Pages(1)

            '加載數字證書(.pfx檔案及秘鑰)
            Dim cert As New PdfCertificate("test.pfx", "123456")

            '加載簽名圖檔
            Dim image As Spire.Pdf.Graphics.PdfImage = Spire.Pdf.Graphics.PdfImage.FromFile("sign.png")

            '添加與圖檔大小相同的簽名到第2頁指定坐标位置
            Dim signature As New PdfSignature(page.Document, page, cert, "sign1")

            '添加數字簽名
            signature.Bounds = New RectangleF(New PointF(400, 700), New SizeF(image.Width, image.Height))

            '設定簽名的頁面坐标位置、大小與圖檔相同
            signature.SignImageSource = image
            signature.GraphicsMode = Spire.Pdf.Security.GraphicMode.SignImageAndSignDetail

            '設定簽名為圖檔模式
            signature.SignImageLayout = Spire.Pdf.Security.SignImageLayout.Stretch
            signature.DocumentPermissions = Spire.Pdf.Security.PdfCertificationFlags.AllowFormFill Or Spire.Pdf.Security.PdfCertificationFlags.AllowComments'文檔權限           

            '配置時間戳伺服器,添加時間戳
            Dim url As String = "Your TimeStamp Server URL"
            signature.ConfigureTimestamp(url)
            'signature.ConfigureTimestamp(url, "Author", "123654");//添加時間戳時設定使用者名和密碼

            '儲存文檔
            pdf.SaveToFile("TimeStamp1.pdf", FileFormat.PDF)
            System.Diagnostics.Process.Start("TimeStamp1.pdf")
        End Sub
    End Class
End Namespace      

簽名時間戳添加結果:

C# 給PDF簽名時添加時間戳的2種方法(附VB.NET代碼)

2. 通過PdfOrdinarySignatureMaker類來簽名,添加時間戳

using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Interactive.DigitalSignatures;
using System.Drawing;
using System.Security.Cryptography.X509Certificates;

namespace TimeStamp2
{
    class Program
    {
        static void Main(string[] args)
        {
            //加載PDF文檔
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile("sample.pdf");

            //加載pfx數字證書及秘鑰
            X509Certificate2 x509 = new X509Certificate2("test.pfx", "123456");

            //執行個體化PdfPKCS7Formatter類的對象
            PdfPKCS7Formatter formatter = new PdfPKCS7Formatter(x509, false);
            formatter.TimestampService = new TSAHttpService("Your TimeStamp Server URL");//配置時間戳伺服器

            //添加簽名
            PdfOrdinarySignatureMaker signatureMaker = new PdfOrdinarySignatureMaker(doc, formatter);            
            IPdfSignatureAppearance signatureAppearance = new PdfCustomSignatureAppearance();
            signatureMaker.MakeSignature("sign", doc.Pages[1], 400, 650, 150, 80, signatureAppearance);
            
            //儲存簽名後的PDF文檔
            doc.SaveToFile("TimeStamp2.pdf", FileFormat.PDF);
            System.Diagnostics.Process.Start("TimeStamp2.pdf");

        }
        public class PdfCustomSignatureAppearance : IPdfSignatureAppearance
        {
            public void Generate(PdfCanvas canvas)
            {
                PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 12), true);
                canvas.DrawString("SIGNED! A CLASS.\n By Tom Smith", font, PdfBrushes.Red, new PointF(0, 0));
            }
        }
    }
}      
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Interactive.DigitalSignatures
Imports System.Drawing
Imports System.Security.Cryptography.X509Certificates

Namespace TimeStamp2
    Class Program
        Private Shared Sub Main(args As String())
            '加載PDF文檔
            Dim doc As New PdfDocument()
            doc.LoadFromFile("sample.pdf")

            '加載pfx數字證書及秘鑰
            Dim x509 As New X509Certificate2("test.pfx", "123456")

            '執行個體化PdfPKCS7Formatter類的對象
            Dim formatter As New PdfPKCS7Formatter(x509, False)
            formatter.TimestampService = New TSAHttpService("Your TimeStamp Server URL")
            '配置時間戳伺服器
            
'添加簽名
            Dim signatureMaker As New PdfOrdinarySignatureMaker(doc, formatter)
            Dim signatureAppearance As IPdfSignatureAppearance = New PdfCustomSignatureAppearance()
            signatureMaker.MakeSignature("sign", doc.Pages(1), 400, 650, 150, 80, _
                signatureAppearance)

            '儲存簽名後的PDF文檔
            doc.SaveToFile("TimeStamp2.pdf", FileFormat.PDF)
            System.Diagnostics.Process.Start("TimeStamp2.pdf")

        End Sub
        Public Class PdfCustomSignatureAppearance
            Implements IPdfSignatureAppearance
            Public Sub Generate(canvas As PdfCanvas)
                Dim font As New PdfTrueTypeFont(New Font("Arial", 12), True)
                canvas.DrawString("SIGNED! A CLASS." & vbLf & " By Tom Smith", font, PdfBrushes.Red, New PointF(0, 0))
            End Sub
        End Class
    End Class
End Namespace      
C# 給PDF簽名時添加時間戳的2種方法(附VB.NET代碼)

以上是本文關于如何在C#程式中給PDF簽名添加時間戳的方法。

内容原創,如需轉載請務必注明出處!

繼續閱讀