'' This code is part of GrapeCity Documents for PDF samples.
'' Copyright (c) GrapeCity, Inc. All rights reserved.
Imports System.IO
Imports System.Drawing
Imports GrapeCity.Documents.Pdf
Imports GrapeCity.Documents.Pdf.AcroForms
Imports GrapeCity.Documents.Text
Imports System.Security.Cryptography.X509Certificates

'' This sample demonstrates how to sign the created PDF with a .pfx file,
'' using a SignatureField.
'' The sample then loads the signed file back into another GcPdfDocument instance
'' and verifies the signature.
Public Class SignDoc
    Function CreatePDF(ByVal stream As Stream) As Integer
        Dim doc = New GcPdfDocument()
        Dim page = doc.NewPage()
        Dim tf = New TextFormat() With {.Font = StandardFonts.Times, .FontSize = 14}
                "Hello, World!" + vbCrLf + "Signed below by GcPdfWeb SignDoc sample." + vbCrLf + "(Note that some browser built-in viewers may not show the signature.)",
                tf, New PointF(72, 72))

        '' Init a test certificate:
        Dim pfxPath = Path.Combine("Resources", "Misc", "GcPdfTest.pfx")
        Dim cert = New X509Certificate2(File.ReadAllBytes(pfxPath), "qq",
                X509KeyStorageFlags.MachineKeySet Or X509KeyStorageFlags.PersistKeySet Or X509KeyStorageFlags.Exportable)
        Dim sp = New SignatureProperties()
        sp.Certificate = cert
        sp.Location = "GcPdfWeb Sample Browser"
        sp.SignerName = "GcPdfWeb"

        '' Init a signature field to hold the signature:
        Dim sf = New SignatureField()
        sf.Widget.Rect = New RectangleF(72, 72 * 2, 72 * 4, 36)
        sf.Widget.Page = page
        sf.Widget.BackColor = Color.LightSeaGreen
        sf.Widget.TextFormat.Font = StandardFonts.Helvetica
        sf.Widget.ButtonAppearance.Caption = $"Signer: {sp.SignerName}{vbCrLf}Location: {sp.Location}"
        '' Add the signature field to the document:

        '' Connect the signature field and signature props:
        sp.SignatureField = sf

        '' Sign and save the document:
        '' NOTES:
        '' - Signing and saving is an atomic operation, the two cannot be separated.
        '' - The stream passed to the Sign() method must be readable.
        doc.Sign(sp, stream)

        '' Rewind the stream to read the document just created
        '' into another GcPdfDocument and verify the signature:
        stream.Seek(0, SeekOrigin.Begin)
        Dim doc2 = New GcPdfDocument()
        Dim sf2 = DirectCast(doc2.AcroForm.Fields(0), SignatureField)
        If Not sf2.Value.VerifySignature() Then
            Throw New Exception("Failed to verify the signature")
        End If
        '' Done (the generated and signed docment has already been saved to 'stream').
        Return doc.Pages.Count
    End Function
End Class