VisualSignature.vb
  1. '' 完毕:
  2. Imports System.IO
  3. Imports System.Drawing
  4. Imports GrapeCity.Documents.Pdf
  5. Imports GrapeCity.Documents.Pdf.AcroForms
  6. Imports GrapeCity.Documents.Text
  7. Imports GrapeCity.Documents.Drawing
  8. Imports GCTEXT = GrapeCity.Documents.Text
  9. Imports GCDRAW = GrapeCity.Documents.Drawing
  10. Imports System.Security.Cryptography.X509Certificates
  11.  
  12. '' 此示例演示了如何使用 .pfx 文件创建 PDF 并对其进行签名,
  13. '' 使用 SignatureField 和签名图像。
  14. '' 然后,该示例将签名的文件加载回另一个 GcPdfDocument 实例
  15. '' 并验证签名。
  16. '' 这个示例与 SignDoc 相同,但添加了代表签名的图像。
  17. Public Class VisualSignature
  18. Function CreatePDF(ByVal stream As Stream) As Integer
  19. Dim doc = New GcPdfDocument()
  20. Dim page = doc.NewPage()
  21. Dim tf = New TextFormat() With {.Font = StandardFonts.Times, .FontSize = 14}
  22. page.Graphics.DrawString("你好世界!" +
  23. "下面由 DsPdfWeb VisualSignature 示例签名。",
  24. tf, New PointF(72, 72))
  25.  
  26. '' 初始化测试证书:
  27. Dim pfxPath = Path.Combine("Resources", "Misc", "DsPdfTest.pfx")
  28. Dim cert = New X509Certificate2(File.ReadAllBytes(pfxPath), "qq",
  29. X509KeyStorageFlags.MachineKeySet Or X509KeyStorageFlags.PersistKeySet Or X509KeyStorageFlags.Exportable)
  30. Dim sp = New SignatureProperties() With
  31. {
  32. .SignatureBuilder = New Pkcs7SignatureBuilder() With {
  33. .CertificateChain = New X509Certificate2() {cert}
  34. },
  35. .Location = "DsPdfWeb Demo Browser",
  36. .SignerName = "DsPdfWeb"
  37. }
  38.  
  39. '' 添加代表签名的图像:
  40. sp.SignatureAppearance.Image = GCDRAW.Image.FromFile(Path.Combine("Resources", "ImagesBis", "signature.png"))
  41. sp.SignatureAppearance.CaptionImageRelation = GrapeCity.Documents.Pdf.Annotations.CaptionImageRelation.ImageOnly
  42.  
  43. '' 初始化一个签名字段来保存签名:
  44. Dim sf = New SignatureField()
  45. sf.Widget.Rect = New RectangleF(72, 72 * 2, 72 * 4, 36)
  46. sf.Widget.Page = page
  47. sf.Widget.BackColor = Color.LightSeaGreen
  48. sf.Widget.DefaultAppearance.Font = StandardFonts.Helvetica
  49. sf.Widget.ButtonAppearance.Caption = $"Signer: {sp.SignerName}{vbCrLf}Location: {sp.Location}"
  50. '' 将签名字段添加到文档中:
  51. doc.AcroForm.Fields.Add(sf)
  52. '' 连接签名字段和签名属性:
  53. sp.SignatureField = sf
  54.  
  55. '' 签署并保存文档:
  56. '' 笔记:
  57. '' - 签名和保存是一个原子操作,两者不能分开。
  58. '' - 传递给 Sign() 方法的流必须可读。
  59. doc.Sign(sp, stream)
  60.  
  61. '' 倒回流以读取刚刚创建的文档
  62. '' 进入另一个 GcPdfDocument 并验证签名:
  63. stream.Seek(0, SeekOrigin.Begin)
  64. Dim doc2 = New GcPdfDocument()
  65. doc2.Load(stream)
  66. Dim sf2 = CType(doc2.AcroForm.Fields(0), SignatureField)
  67. If Not sf2.Value.VerifySignatureValue() Then
  68. Throw New Exception("Failed to verify the signature")
  69. End If
  70.  
  71. '' 完成(生成并签名的文档已保存到“流”)。
  72. Return doc.Pages.Count
  73. End Function
  74. End Class
  75.