NoPassAddAnnotation.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 GrapeCity.Documents.Pdf
Imports GrapeCity.Documents.Pdf.Annotations

'' This example shows how to load a password protected PDF without specifying the password,
'' and add a square annotation (a red border along the sides of the page) to the first page of the PDF.
'' The modified PDF is saved and re-opened with the password so that we can show it in the demo.
Public Class NoPassAddAnnotation
    Public Function CreatePDF(ByVal stream As Stream) As Integer
        Using fsSrc = File.OpenRead(Path.Combine("Resources", "PDFs", "Wetlands-password-user.pdf"))
            '' Set up DecryptionOptions to allow loading password protected PDFs without password:
            Dim dopt = New DecryptionOptions() With {.ThrowExceptionIfInvalidPassword = False}
            Dim docSrc = New GcPdfDocument()
            docSrc.Load(fsSrc, dopt)

            '' Add a square annotation to the first page of the PDF:
            Dim page = docSrc.Pages(0)
            Dim pageSize = page.Size
            Dim sa = New SquareAnnotation() With {
                .Page = page,
                .Rect = New RectangleF(36, 36, pageSize.Width - 72, pageSize.Height - 72),
                .Color = Color.Red
            }
            ' Note: we must remove the UserName, as it is initialized by default which will cause an exception
            ' when the document is saved, because strings cannot be encrypted:
            sa.UserName = Nothing

            '' Demo site specific:
            ' We save the modified password protected document to a temp file,
            ' and load it again with the password, so that the demo site can show it
            ' without asking the user for a password:
            Dim fn = Path.GetTempFileName()
            docSrc.Save(fn)
            Dim doc = New GcPdfDocument()
            Using fs = File.OpenRead(fn)
                doc.Load(fs, "user")
                doc.Save(stream)
            End Using
            File.Delete(fn)
            '' Done:
            Return docSrc.Pages.Count
        End Using
    End Function
End Class