TransparencyLayer.vb
''
'' This code is part of Document Solutions for PDF .NET demos.
'' Copyright (c) MESCIUS inc. All rights reserved.
''
Imports System.IO
Imports System.Drawing
Imports System.Numerics
Imports GrapeCity.Documents.Pdf
Imports GrapeCity.Documents.Text
Imports GCTEXT = GrapeCity.Documents.Text
Imports GCDRAW = GrapeCity.Documents.Drawing

Public Class TransparencyLayer
    Public 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("DsPdf Demo")
                tl.DefaultFormat.Font = GCTEXT.Font.FromFile(Path.Combine("Resources", "Fonts", "NotoSans-Bold.ttf"))
                tl.DefaultFormat.FontSize = g.Resolution
                tl.DefaultFormat.ForeColor = Color.Blue
                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(
                    CSng((tl.ContentWidth * Math.Cos(angle) - tl.ContentHeight * Math.Sin(angle)) / 2),
                    CSng((tl.ContentWidth * Math.Sin(angle) + tl.ContentHeight * Math.Cos(angle)) / 2))

                ' Create semi-opaque transparency layer. All subsequent drawing operations
                ' will be drawn using the specified opacity till the PopTransparencyLayer() call:
                g.PushTransparencyLayer(Nothing, 0.5F)

                ' Draw watermark text diagonally in the center of the page
                ' (matrix transforms are applied from last to first):
                g.Transform =
                    Matrix3x2.CreateRotation(CSng(angle)) *
                    Matrix3x2.CreateTranslation(center.X - delta.X, center.Y - delta.Y)
                g.DrawTextLayout(tl, PointF.Empty)
                ' Add a border around the text, it will also be drawn semi-transparently:
                Dim rc = New RectangleF(-30, -20, tl.ContentWidth + 60, tl.ContentHeight + 40)
                g.DrawRoundRect(rc, 30, New GCDRAW.Pen(Color.DarkOrange, 8))
                g.Transform = Matrix3x2.Identity

                ' Pop transparency layer:
                g.PopTransparencyLayer()
            Next
            doc.Save(stream)
            Return doc.Pages.Count
        End Using
    End Function
End Class