''
'' 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 try to read its metadata.
'' Keep in mind that in some cases metadata in a PDF may also be encrypted, in which case
'' reading it without the password is impossible.
'' For reference, the loaded PDF is protected with the owner password 'owner' and user password 'user'.
Public Class NoPassGetMetadata
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)
'' 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}
'' 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
If Not metadataIsEncrypted Then
Dim m As Metadata = docSrc.Metadata
tl.AppendLine("The PDF has unencrypted metadata:", captionFmt)
tl.AppendLine($" Copyright: {m.Copyright}")
tl.AppendLine($" CreatorTool: {m.CreatorTool}")
If m.CreateDate.HasValue Then
tl.AppendLine($" CreateDate: {m.CreateDate.Value.ToUniversalTime():R}")
End If
tl.AppendLine($" Description: {m.Description}")
If m.ModifyDate.HasValue Then
tl.AppendLine($" ModifyDate: {m.ModifyDate.Value.ToUniversalTime():R}")
End If
tl.AppendLine($" Producer: {m.Producer}")
tl.AppendLine($" Title: {m.Title}")
Else
tl.AppendLine("Cannot read metadata because the PDF metadata is encrypted.", captionFmt)
End If
'' Render the results:
tl.PerformLayout(True)
While True
Dim rest As TextLayout = Nothing
Dim splitResult = tl.Split(Nothing, rest)
page.Graphics.DrawTextLayout(tl, PointF.Empty)
If splitResult <> SplitResult.Split Then
Exit While
End If
tl = rest
tl.MarginTop = tl.Resolution
page = doc.Pages.Add()
End While
'' Done:
doc.Save(stream)
Return doc.Pages.Count
End Using
End Function
End Class