SignDoc.vb
  1. ''
  2. '' This code is part of Document Solutions for PDF demos.
  3. '' Copyright (c) MESCIUS inc. All rights reserved.
  4. ''
  5. Imports System.IO
  6. Imports System.Drawing
  7. Imports GrapeCity.Documents.Pdf
  8. Imports GrapeCity.Documents.Pdf.AcroForms
  9. Imports GrapeCity.Documents.Text
  10. Imports System.Security.Cryptography.X509Certificates
  11.  
  12. '' This sample demonstrates how to sign the created PDF with a .pfx file,
  13. '' using a SignatureField.
  14. '' The sample then loads the signed file back into another GcPdfDocument instance
  15. '' and verifies the signature.
  16. Public Class SignDoc
  17. Function CreatePDF(ByVal stream As Stream) As Integer
  18. Dim doc = New GcPdfDocument()
  19. Dim page = doc.NewPage()
  20. Dim tf = New TextFormat() With {.Font = StandardFonts.Times, .FontSize = 14}
  21. page.Graphics.DrawString("Hello, World!" + vbLf +
  22. "Signed by DsPdfWeb SignDoc sample.",
  23. tf, New PointF(72, 72))
  24.  
  25. '' Init a test certificate:
  26. Dim pfxPath = Path.Combine("Resources", "Misc", "DsPdfTest.pfx")
  27. Dim cert = New X509Certificate2(File.ReadAllBytes(pfxPath), "qq",
  28. X509KeyStorageFlags.MachineKeySet Or X509KeyStorageFlags.PersistKeySet Or X509KeyStorageFlags.Exportable)
  29. Dim sp = New SignatureProperties() With {
  30. .SignatureBuilder = New Pkcs7SignatureBuilder() With {.CertificateChain = New X509Certificate2() {cert}},
  31. .Location = "DsPdfWeb Demo Browser",
  32. .SignerName = "DsPdfWeb",
  33. .SigningDateTime = Util.TimeNow()
  34. }
  35.  
  36. '' Init a signature field to hold the signature:
  37. Dim sf = New SignatureField()
  38. sf.Widget.Rect = New RectangleF(72, 72 * 2, 72 * 4, 36)
  39. sf.Widget.Page = page
  40. sf.Widget.BackColor = Color.LightSeaGreen
  41. sf.Widget.DefaultAppearance.Font = StandardFonts.Helvetica
  42. sf.Widget.ButtonAppearance.Caption = $"Signer: {sp.SignerName}{vbCrLf}Location: {sp.Location}"
  43. '' Add the signature field to the document:
  44. doc.AcroForm.Fields.Add(sf)
  45.  
  46. '' Connect the signature field and signature props:
  47. sp.SignatureField = sf
  48.  
  49. '' Sign and save the document:
  50. '' NOTES:
  51. '' - Signing and saving is an atomic operation, the two cannot be separated.
  52. '' - The stream passed to the Sign() method must be readable.
  53. doc.Sign(sp, stream)
  54.  
  55. '' Rewind the stream to read the document just created
  56. '' into another GcPdfDocument and verify the signature:
  57. stream.Seek(0, SeekOrigin.Begin)
  58. Dim doc2 = New GcPdfDocument()
  59. doc2.Load(stream)
  60. Dim sf2 = DirectCast(doc2.AcroForm.Fields(0), SignatureField)
  61. If Not sf2.Value.VerifySignatureValue() Then
  62. Throw New Exception("Failed to verify the signature")
  63. End If
  64. ''
  65. '' Done (the generated and signed document has already been saved to 'stream').
  66. Return doc.Pages.Count
  67. End Function
  68. End Class
  69.