NoPassSetMetadata.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.Security
Imports GrapeCity.Documents.Text

'' This example shows how to load a password protected PDF and change its metadata.
'' Keep in mind that in some cases metadata in a PDF may also be encrypted, in which case
'' accessing it without the password is impossible.
'' For reference, the loaded PDF is protected with the owner password 'owner' and user password 'user'.
Public Class NoPassSetMetadata
    Public Function CreatePDF(ByVal stream As Stream) As Integer
        Using fs = 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(fs, dopt)

            '' All security handlers before StandardSecurityHandlerRev4 always encrypted metadata,
            ' the StandardSecurityHandlerRev4 has EncryptMetadata property which we need to check:
            Dim metadataIsEncrypted As Boolean = True
            If TypeOf docSrc.Security.EncryptHandler Is StandardSecurityHandlerRev4 Then
                Dim ssh = DirectCast(docSrc.Security.EncryptHandler, StandardSecurityHandlerRev4)
                metadataIsEncrypted = ssh.EncryptMetadata
            End If
            ' In the PDF used by this demo the metadata is not encrypted:
            If metadataIsEncrypted Then
                Throw New Exception("Set PDF Metadata demo: Unexpected error.")
            End If

            '' Save original metadata so we can compare the results:
            Dim m As Metadata = docSrc.Metadata
            Dim origTitle = m.Title
            Dim origCreatorTool = m.CreatorTool
            Dim origModifyDate = m.ModifyDate
            ' Change some metadata:
            m.Title = "Set PDF Metadata Demo"
            m.CreatorTool = "DsPdf Demo Browser"
            m.ModifyDate = Util.TimeNow()

            '' We save the modified password protected document to a temp file,
            ' load it again (also without password), read the (modified) metadata
            ' and display it in the resulting PDF:
            Dim fn = Path.GetTempFileName()
            docSrc.Save(fn)

            Using fsTemp = File.OpenRead(fn)
                Dim docTemp = New GcPdfDocument()
                docTemp.Load(fsTemp, dopt)

                '' The PDF to hold the results:
                Dim doc = New GcPdfDocument()
                Dim page = doc.NewPage()
                ' Set up a TextLayout to format the results:
                Dim tl = page.Graphics.CreateTextLayout()
                tl.DefaultFormat.Font = StandardFonts.Courier
                tl.DefaultFormat.FontSize = 14
                tl.MaxWidth = doc.PageSize.Width
                tl.MaxHeight = doc.PageSize.Height
                tl.MarginAll = tl.Resolution
                Dim captionFmt = New TextFormat(tl.DefaultFormat) With {.Font = StandardFonts.CourierBold, .FontSize = tl.DefaultFormat.FontSize + 2}

                If TypeOf docTemp.Security.EncryptHandler Is StandardSecurityHandlerRev4 Then
                    Dim sshTemp = DirectCast(docTemp.Security.EncryptHandler, StandardSecurityHandlerRev4)
                    metadataIsEncrypted = sshTemp.EncryptMetadata
                End If
                If metadataIsEncrypted Then
                    Throw New Exception("Set PDF Metadata demo: Unexpected error.")
                End If

                '' Render the results:
                Dim mTemp As Metadata = docTemp.Metadata
                tl.AppendLine("Modified metadata in a password protected PDF:", captionFmt)
                tl.AppendLine($"{vbLf}Title", captionFmt)
                tl.AppendLine($"Was '{origTitle}', now '{mTemp.Title}'")
                tl.AppendLine($"{vbLf}CreatorTool", captionFmt)
                tl.AppendLine($"Was '{origCreatorTool}', now '{mTemp.CreatorTool}'")
                tl.AppendLine($"{vbLf}ModifyDate", captionFmt)
                Dim origModifyDateStr = If(origModifyDate.HasValue, origModifyDate.Value.ToUniversalTime().ToString("R"), String.Empty)
                Dim newModifyDateStr = If(mTemp.ModifyDate.HasValue, mTemp.ModifyDate.Value.ToUniversalTime().ToString("R"), String.Empty)
                tl.AppendLine($"Was '{origModifyDateStr}', now '{newModifyDateStr}'")
                tl.PerformLayout(True)
                page.Graphics.DrawTextLayout(tl, PointF.Empty)
                doc.Save(stream)
            End Using
            File.Delete(fn)

            '' Done:
            Return 1
        End Using
    End Function
End Class