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

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

一、程序運行環境

  • 編譯環境:Visual Studio/.NetFramework 4.8
  • 所需測試文件:PDF、.pfx數字證書及秘鑰、PDF類庫(spire.pdf.dll 7.5.7)
  • 可信時間戳服務器:URL地址

註:VS程序中,在“解決方案資源管理器中”先引用spire.pdf.dll文件,如下圖,

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

二、程序代碼

添加簽名時,這裡可分別通過兩個類來實現,即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

簽名時間戳添加結果:

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

C#

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));
            }
        }
    }
}

VB.NET

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簽名添加時間戳 內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: