Get PDF Info
Page count and encryption status are the two things you usually want before deciding what to do with a file. Both come off the reader, but the order of the calls matters for encrypted documents, because an encrypted file has no readable page tree until it has been decrypted.
Doing it
f, err := os.Open(inputPath)
if err != nil {
return err
}
defer f.Close()
pdfReader, err := model.NewPdfReader(f)
if err != nil {
return err
}
isEncrypted, err := pdfReader.IsEncrypted()
if err != nil {
return err
}
if isEncrypted {
auth, err := pdfReader.Decrypt([]byte("")) // or the real password
if err != nil {
return err
}
if !auth {
return errors.New("password required")
}
}
numPages, err := pdfReader.GetNumPages()model.NewPdfReader is the deliberate choice here. It does not attempt decryption, so
it returns successfully for an encrypted file and leaves you to call Decrypt yourself.
The other constructors, NewPdfReaderFromFile and NewPdfReaderWithOpts, try the
password from ReaderOpts (the empty string by default) and fail outright with “unable
to decrypt password protected file” when that does not authenticate. Use those when you
already have the password; use NewPdfReader when you want to report on files you
cannot open.
Decrypt reloads the document structure on success, which is why GetNumPages comes
after it.
Limitations
Calling GetNumPages on an undecrypted encrypted document returns the error “file need
to be decrypted first” rather than zero. The same guard sits in front of page access, so
there is no way to count pages without authenticating first.
Decrypt returning false means the password was wrong, not that something failed. The
error return is reserved for a malformed encryption dictionary. Authenticating with the
user password rather than the owner password still opens the file, but the document’s
permission flags then apply; CheckAccessRights(password) returns those permissions
alongside the viewable flag if you need to tell the two apart, and
GetEncryptionMethod() describes the scheme in use.
Neither call says anything about the document’s own metadata. Title, author, producer and
creation date live in the information dictionary, reachable through
pdfReader.GetPdfInfo(), and the file’s PDF version through pdfReader.PdfVersion().
The metadata guides cover those.
Run the example
getPdfProperties opens each file named on the command line and returns a
PdfProperties value holding the page count, the encryption flag, and whether the
document is viewable without a password.
git clone https://github.com/unidoc/unipdf-examples.git
cd unipdf-examples/analysis
go run pdf_info.go input1.pdf [input2.pdf] ...If this is your first time using UniPDF, follow the getting started guide to create an API key and set up your development environment.
View the full source
Sample output
Input file: templates/documentation/unipdf-templates-documentation.pdf
Num Pages: 58
Is Encrypted: false
Is Viewable (without pass): true