Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

With Apache PDFBox 2.0, protect a generated PDF by configuring an AccessPermission, creating a StandardProtectionPolicy, calling document.protect(policy), and then saving the document. Choose whether recipients need a password to open the file separately from whether you want to restrict actions such as printing or copying. These settings express PDF permissions; they should not be treated as guaranteed digital rights management.

Choose what “protect” means for your PDF

PDFBox distinguishes a password used to open a document from an owner password used to access it with all permissions. The user password can be empty, so a recipient can open the PDF without entering a password while the document still carries permission settings. The owner password and user password serve different purposes; do not assume that disabling printing automatically makes the file require an opening password.

The PDFBox 2.0 encryption cookbook describes the user password as enabling opening and viewing with restricted permissions, and the owner password as providing access with all permissions. Decide which user experience you need before choosing the values:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Require a password to open: Set a non-empty user password. Give the intended recipient that password through an appropriately separate channel.
  • Allow opening without a password but set restrictions: Use an empty user password and set the permissions you need to deny. This is the cookbook sample’s pattern.
  • Allow unrestricted access to people with the owner password: Set and protect an owner password. The owner password is not a substitute for the user password when your goal is to require a password just to open.

Use only restrictions that match the requirement. For example, disabling content extraction is distinct from disabling printing. Permission flags communicate intended limits to PDF readers; the cited PDFBox documentation does not establish that every viewer enforces them identically. If your requirement is confidentiality, requiring an opening password is a different control from merely disabling a user action.

PDFBox version: keep the 2.x example on the 2.x API

The code below follows the PDFBox 2.0 cookbook and its API documentation. The project homepage reports PDFBox 2.0.37 released July 15, 2026, and PDFBox 3.0.8 released July 11, 2026. Those release facts do not make 2.x loading or dependency examples interchangeable with 3.x: verify the APIs against the exact major version in your application. The PDFBox 2.0.1 StandardProtectionPolicy API page documents the policy class, while the cookbook documents the protection sequence.

The example assumes your application has already created a PDDocument in memory and has an output destination. It shows the protection-and-save portion rather than inventing a version-specific PDF creation lifecycle. For an existing generated document, call this code before the final output is saved or returned.

Protect and save the generated document

import java.io.File;
import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;

public class ProtectGeneratedPdf {
    /**
     * Apply PDFBox 2.0 password and permission protection, then save.
     * The caller owns and must close the PDDocument.
     */
    public static void protectAndSave(
            PDDocument document,
            File outputFile,
            String ownerPassword,
            String userPassword) throws IOException {

        AccessPermission permissions = new AccessPermission();
        permissions.setCanPrint(false);
        permissions.setCanExtractContent(false);

        StandardProtectionPolicy policy = new StandardProtectionPolicy(
                ownerPassword,
                userPassword,
                permissions);
        policy.setEncryptionKeyLength(256);

        document.protect(policy);
        document.save(outputFile);
    }
}

Call protectAndSave after your code has finished adding pages and content, but before it closes the document. For example, if your existing generation flow already holds a PDDocument called document, invoke protectAndSave(document, new File("protected.pdf"), ownerPassword, userPassword) in that flow. The 256-bit key length is the configuration used in the PDFBox 2.0 cookbook example; it is a documented option, not a claim that every PDF reader or workflow will have identical compatibility.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The order matters: configure permissions, create the policy with both passwords, optionally set the key length, call document.protect(policy), and save the protected output. Saving before calling protect leaves that earlier file outside this protection operation. Close the document in the code that owns its lifecycle, including when saving throws an exception; do not close it inside this helper if the caller still manages it.

Replace the sample booleans according to the actions you intend to permit. The cookbook sample disables printing and content extraction; it does not mean every application should disable both. The documented cookbook also discusses 40-, 128- and 256-bit key-length choices. Confirm the exact methods and behavior for the PDFBox version you use rather than copying this 2.x code into a 3.x project unchanged.

Handle passwords as secrets

Do not put real owner or user passwords in source code, committed configuration files, logs, command-line arguments recorded by your deployment environment, or error messages. Supply them through your application’s established secret-management or secure configuration flow. Use distinct values where your security design calls for separate owner and user access. If the user password is intentionally empty, make that decision explicit in configuration and documentation: the resulting PDF is not password-gated for opening.

Also plan how recipients obtain passwords and how you will handle rotation or forgotten credentials. Password-based encryption does not provide a password recovery route in this code. A PDF file and its password sent together through the same channel may undermine the intended separation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Check the result in the viewer your recipients use

After saving, test the output using the PDF readers and workflows that matter to your recipients. Verify that the file opens as expected, prompts for a password when required, and presents the intended permission behavior. Do not infer successful protection solely from a successful save call. PDF permissions are interpreted by viewer software, and the cited documentation does not establish uniform enforcement across readers.

  • For an empty user password, confirm that opening does not prompt for one.
  • For a non-empty user password, confirm that opening does prompt and that the password works.
  • Check the selected printing and extraction restrictions using the intended viewer.
  • Keep an unprotected source or regeneration path according to your retention requirements; do not assume that a recipient’s copy can be restored if passwords are lost.

Troubleshoot common problems

The output opens without asking for a password

Check whether the user password passed to StandardProtectionPolicy is empty. In the cookbook pattern, an empty user password allows opening without a password even though permission settings are applied. Use a non-empty user password if opening itself must be gated.

Printing or copying still appears to work

Verify that the corresponding AccessPermission flag is disabled and that document.protect(policy) runs before the saved output is created. Then test with the actual target viewer. The permission flags express restrictions, but the documentation does not promise identical enforcement by all PDF software.

The generated file seems unchanged

Check that you are examining the output produced by the save call after protection, not an earlier copy. The documented sequence applies the policy to the document and then saves it; changing permissions after the output has already been written does not update that previous file.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The code does not compile in a PDFBox 3.x project

This example is for the PDFBox 2.0 API line. Check the documentation and API for your exact dependency version before adapting it; do not treat a 2.x example as a verified 3.x implementation.

You need encryption but do not want password-based access

PDFBox is not the only Java library to evaluate. The iText encryption article describes password-based and certificate-based encryption options. Compare the approach with your project’s existing dependencies, licensing requirements, intended readers, and compatibility needs rather than changing libraries solely to obtain a different permission flag.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

PDFBox or iText?

Apache PDFBox is an Apache-licensed Java project for creating and manipulating PDFs, with documented password protection. iText also documents Java PDF encryption and describes AES-128 and AES-256, cautions against RC4, and discusses PDF 1.7 with AES-256 as a broad-compatibility choice. Its article also describes PDF 2.0 with AES-GCM and MAC protection as a newer option, and says support for relevant ISO extensions was added in iText Core 9.0.0. These are iText’s recommendations; validate compatibility with the actual readers and systems you must support before selecting a format.

There is no universal library choice established by those facts. Existing dependencies, licensing requirements, target-viewer compatibility, and whether password-based or certificate-based encryption is required are practical decision points. Review the current terms for your intended iText use case; the sources cited here do not establish a license recommendation for any particular application.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For the specific PDFBox 2.0 route, use the official encryption cookbook alongside the version-matched API documentation. For iText’s stated algorithms and compatibility guidance, consult How does iText handle PDF encryption?.

Or skip the browser setup

If your actual task is to capture a web page as a PDF rather than protect a PDF your Java application already generated, ScreenshotNeo offers a one-request screenshot API. It creates a PDF from a page; it does not apply the PDFBox password and permission protection described above. For a PNG/JPEG/WebP screenshot instead, a basic cURL request is:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for PDF output and other capture options. Before capture, it can accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and responses identify the page verdict and billing status in headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.

Sign up for ScreenshotNeo free: 1,000 screenshots a month, no card required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can I protect a PDF that my Java application has already saved?

The example applies protection to a PDFBox document object before saving the protected output. The cited cookbook shows loading an existing PDF before protection; confirm the complete load-and-protect lifecycle for your exact PDFBox version.

Does disabling printing or copying prevent every recipient from doing it?

The permission flags express restrictions, but the documentation cited here does not establish identical enforcement in every PDF viewer.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.