AddWatermark.vb
''
'' This code is part of GrapeCity Documents for PDF samples.
'' Copyright (c) GrapeCity, Inc. All rights reserved.
''
Imports System
Imports System.IO
Imports System.Drawing
Imports System.Numerics
Imports GrapeCity.Documents.Pdf
Imports GrapeCity.Documents.Text

'' This sample shows how to add a simple text watermark-Like overlay
'' to all pages of an existing PDF.
Public Class AddWatermark
    Function CreatePDF(ByVal stream As Stream) As Integer
        Dim doc = New GcPdfDocument()
        Using fs = File.OpenRead(Path.Combine("Resources", "PDFs", "SlidePages.pdf"))
            doc.Load(fs)
            For Each page In doc.Pages
                Dim g = page.Graphics

                '' Text layout used to draw the 'watermark':
                Dim tl = g.CreateTextLayout()
                tl.Append("GcPdf Demo")
                tl.DefaultFormat.Font = Font.FromFile(Path.Combine("Resources", "Fonts", "calibrib.ttf"))
                tl.DefaultFormat.FontSize = g.Resolution
                '' Semi-transparent color:
                tl.DefaultFormat.ForeColor = Color.FromArgb(128, Color.Yellow)
                tl.DefaultFormat.GlyphAdvanceFactor = 1.5F
                tl.PerformLayout()

                '' Rotation angle (radians) - from left/bottom to right/top corners of the page:
                Dim angle = -Math.Asin(g.CanvasSize.Width / g.CanvasSize.Height)
                '' Page center:
                Dim center = New PointF(g.CanvasSize.Width / 2, g.CanvasSize.Height / 2)
                '' Additional offset from text size:
                Dim delta = New PointF(
                    ((tl.ContentWidth * Math.Cos(angle) - tl.ContentHeight * Math.Sin(angle)) / 2),
                    ((tl.ContentWidth * Math.Sin(angle) + tl.ContentHeight * Math.Cos(angle)) / 2))

                '' Draw watermark text diagonally in the center of the page
                '' (matrix transforms are applied from last to first):
                g.Transform =
                    Matrix3x2.CreateRotation(angle) *
                    Matrix3x2.CreateTranslation(center.X - delta.X, center.Y - delta.Y)
                g.DrawTextLayout(tl, PointF.Empty)
                g.Transform = Matrix3x2.Identity
            Next
            doc.Save(stream)
        End Using
        Return doc.Pages.Count
    End Function
End Class