Open a document

Open from a path or from bytes, decrypt password-protected files, and read document metadata.

Open parses a file and OpenBytes parses a PDF already in memory. Always Close the document, because it may hold a file handle and caches.

main.go
doc, err := gopdfrab.Open(path)    // or gopdfrab.OpenBytes(data)
if err != nil {
	log.Fatal(err)
}
defer doc.Close()

Opening is tolerant. Broken cross-references, a truncated body or a missing startxref don't fail the open. The damage is recorded as a verification issue (see errors). A file that is not a PDF, or that needs a password, does return an error.

For a one-shot check, skip this step: Verify and Convert also accept a path.

Encrypted PDFs

Files encrypted with the empty user password open transparently. Otherwise pass a password to OpenWithPassword or Options.Password. A missing one returns ErrPasswordRequired. Supported: RC4 40/128-bit, AES-128 and AES-256.

encrypted.go
// Encrypted documents are decrypted transparently on open when they use
// the empty user password. Supply a user or owner password explicitly:
doc, err := gopdfrab.OpenWithPassword(path, []byte("secret"))
if errors.Is(err, gopdfrab.ErrPasswordRequired) {
	log.Fatal("a correct password is required to open this file")
}
defer doc.Close()

// Verify and Convert decrypt the same way, via Options.Password
res, err := gopdfrab.VerifyContext(ctx, path, gopdfrab.PDFA1B, gopdfrab.Options{
	Password: []byte("secret"),
})

PDF/A forbids encryption, so an encrypted file always fails verification. Conversion writes the output unencrypted.

Document helpers

Cheap shortcuts over data the document already holds. They don't re-run verification. ClaimedConformance reports what the producer claims; only Verify tells you whether that's true.

helpers.go
ok, err := doc.IsPDFA()   // shorthand for Verify(PDFA1B).Valid

ok, err = doc.IsPDF()     // shorthand for VerifyObjectModel().Valid

part, level, err := doc.ClaimedConformance() // e.g. "1", "B" -- what the file claims, not whether it's valid

n, err := doc.PageCount()   // number of pages

version, err := doc.Version()  // PDF version from the header, e.g. "1.7"

info, err := doc.Metadata()    // Info dictionary entries (Title, Author, ...)

xmp, err := doc.XMPMetadata()  // raw XMP packet bytes, decoded to UTF-8