Recursive AI

Password-protect a PDF in Go

onepdf-go is a free, open-source PDF library for Go from Recursive AI that reads, edits, signs, redacts and lays out PDFs. MIT or Apache-2.0, no third-party dependencies.

Save an AES-256 copy of input.pdf (“Invoice 1042: USD 240.00”) with onepdf.WithEncryption and a password to open it.

Terminal
go get recursiveai.org/go/onepdf

In the unzipped folder, run go run . with Go 1.26.8.

GO
package main
 
import (
    "log"
 
    "recursiveai.org/go/onepdf"
)
 
func main() {
    doc, err := onepdf.OpenFile("input.pdf")
    if err != nil {
        log.Fatal(err)
    }
    defer doc.Close()
 
    encrypt := onepdf.WithEncryption(
        onepdf.CipherAES256,
        "demo-reader", "demo-owner",
        onepdf.WithPermissions(onepdf.PermPrint),
    )
    if err := doc.SaveFile("locked.pdf", encrypt); err != nil {
        log.Fatal(err)
    }
}

The example is the full program below: unzip it and go run .. To run only the code above, paste it into main.go, run go mod init example and go get recursiveai.org/go/onepdf, then go run ..

If you paste the code, copy input.pdf from the zip into your project folder, or put your own PDF there named input.pdf.

The snippet writes locked.pdf without printing anything.

The full program

The downloadable example also checks that the file won’t open without the password and reads back the permissions.

GO
package main
 
import (
	"errors"
	"fmt"
	"log"
 
	"recursiveai.org/go/onepdf"
)
 
func main() {
	doc := must(onepdf.OpenFile("input.pdf"))
	defer doc.Close()
 
	// Demo passwords for this sample PDF only.
	const user = "demo-reader"
	const owner = "demo-owner"
	encrypt := onepdf.WithEncryption(
		onepdf.CipherAES256, user, owner,
		onepdf.WithPermissions(onepdf.PermPrint),
	)
	const path = "locked.pdf"
	if err := doc.SaveFile(path, encrypt); err != nil {
		log.Fatal(err)
	}
 
	unopened, err := onepdf.OpenFile(path)
	if !errors.Is(err, onepdf.ErrPassword) {
		if unopened != nil {
			unopened.Close()
		}
		log.Fatalf("expected a password error, got %v", err)
	}
	fmt.Println("Without password: rejected")
	locked := must(onepdf.OpenFile(path, onepdf.WithPassword(user)))
	defer locked.Close()
	info, ok := locked.Encryption()
	if !ok || info.Cipher != onepdf.CipherAES256 {
		log.Fatal("expected AES-256")
	}
	fmt.Println("Wrote", path)
	fmt.Println("Reader password: accepted")
	fmt.Println("Cipher:", info.Cipher)
	fmt.Println("Print allowed:", locked.Permissions().Has(onepdf.PermPrint))
	fmt.Println("Copy allowed:", locked.Permissions().Has(onepdf.PermCopy))
}
 
func must[T any](value T, err error) T {
	if err != nil {
		log.Fatal(err)
	}
	return value
}

The program prints:

Text
Without password: rejected
Wrote locked.pdf
Reader password: accepted
Cipher: aes256
Print allowed: true
Copy allowed: false

Open locked.pdf with demo-reader to try the output; use separate, strong passwords in your application instead of the two demo values. PDF permission flags are data for readers that honor them; onepdf-go does not enforce them.

Variations

Allow both printing and copying. Replace the WithPermissions option in the snippet:

GO
onepdf.WithPermissions(
    onepdf.PermPrint | onepdf.PermCopy,
),

The program now prints Copy allowed: true; opening without the password still fails.

The short answer

To password-protect a PDF in Go, open the original and call SaveFile with onepdf.WithEncryption(onepdf.CipherAES256, user, owner, ...). Supply a nonempty user password and a different owner password. Use onepdf.WithPermissions to set what a compliant viewer should allow someone who opens the file with the user password to do. The program checks the saved output, rather than assuming that a successful save means it prompts for a password.

How can I require a password to open a PDF?

The user password is the open password you give to the recipient. The owner password also opens the file and gives unrestricted access. An empty user password lets anyone open the file, even when the file is encrypted. An empty owner password falls back to the user password, which defeats the separation between reader and owner. Reject empty values before generating a file that must prompt for a password. Keep the owner password private, and don’t put either password in logs or in the filename.

Test the file you plan to send: open it without a password and expect onepdf.ErrPassword; open it again with onepdf.WithPassword and verify that the intended reader password works. The example performs both checks against locked.pdf. It doesn’t modify the original input.pdf, which remains unencrypted.

Can I password-protect a PDF and still let people print it?

Yes. Access to the encrypted PDF and permissions for the opened document are separate. The sample sets the print flag and leaves the copy and modify flags unset. To allow full-quality printing, add onepdf.PermPrintHighQuality alongside onepdf.PermPrint. If you omit WithPermissions, all flags are set by default. An application that honors permissions can inspect the flags and check whether the document was opened as owner.

Permissions are not a way to make readable content impossible to copy. A viewer may ignore the flags, and a reader can still capture content they can see. If a recipient must never see part of a document, remove that content from the shared copy instead of relying on a no-copy rule.

Can I password-protect a PDF I already have?

Yes. The example opens an existing PDF and writes a complete encrypted copy; it does not depend on how the PDF was originally produced. WithEncryption is an option for a full save, not SaveIncremental. A save without the option keeps the existing encryption state. Keep an original separately if you need it for editing, and check that any downstream viewer can open the AES-256 copy before you send it.

All onepdf Go recipes