AddWatermark.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
  6. Imports System.IO
  7. Imports System.Drawing
  8. Imports System.Numerics
  9. Imports GrapeCity.Documents.Pdf
  10. Imports GrapeCity.Documents.Text
  11. Imports GCTEXT = GrapeCity.Documents.Text
  12. Imports GCDRAW = GrapeCity.Documents.Drawing
  13.  
  14. '' This sample shows how to add a simple text watermark-Like overlay
  15. '' to all pages of an existing PDF.
  16. Public Class AddWatermark
  17. Function CreatePDF(ByVal stream As Stream) As Integer
  18. Dim doc = New GcPdfDocument()
  19. Using fs = File.OpenRead(Path.Combine("Resources", "PDFs", "SlidePages.pdf"))
  20. doc.Load(fs)
  21. For Each page In doc.Pages
  22. Dim g = page.Graphics
  23.  
  24. '' Text layout used to draw the 'watermark':
  25. Dim tl = g.CreateTextLayout()
  26. tl.Append("DsPdf Demo")
  27. tl.DefaultFormat.Font = GCTEXT.Font.FromFile(Path.Combine("Resources", "Fonts", "calibrib.ttf"))
  28. tl.DefaultFormat.FontSize = g.Resolution
  29. '' Semi-transparent color:
  30. tl.DefaultFormat.ForeColor = Color.FromArgb(128, Color.Yellow)
  31. tl.DefaultFormat.GlyphAdvanceFactor = 1.5F
  32. tl.PerformLayout()
  33.  
  34. '' Rotation angle (radians) - from left/bottom to right/top corners of the page:
  35. Dim angle = -Math.Asin(g.CanvasSize.Width / g.CanvasSize.Height)
  36. '' Page center:
  37. Dim center = New PointF(g.CanvasSize.Width / 2, g.CanvasSize.Height / 2)
  38. '' Additional offset from text size:
  39. Dim delta = New PointF(
  40. ((tl.ContentWidth * Math.Cos(angle) - tl.ContentHeight * Math.Sin(angle)) / 2),
  41. ((tl.ContentWidth * Math.Sin(angle) + tl.ContentHeight * Math.Cos(angle)) / 2))
  42.  
  43. '' Draw watermark text diagonally in the center of the page
  44. '' (matrix transforms are applied from last to first):
  45. g.Transform =
  46. Matrix3x2.CreateRotation(angle) *
  47. Matrix3x2.CreateTranslation(center.X - delta.X, center.Y - delta.Y)
  48. g.DrawTextLayout(tl, PointF.Empty)
  49. g.Transform = Matrix3x2.Identity
  50. Next
  51. doc.Save(stream)
  52. End Using
  53. Return doc.Pages.Count
  54. End Function
  55. End Class
  56.