I found the solution to this problem. It would appear that if the PDF comes from an external source, sometimes the PDF is protected or encrypted.

If you get a blank output when loading up a PDF document from an external source and add protections you are probably working with an encrypted document. I have a stream processing system working on PDF documents. So the following code works for me. If you are just working with PDF inputs then you could integrate the below code with your flow.

public InputStream convertDocument(InputStream dataStream) throws Exception {
    // just acts as a pass through since already in pdf format
    PipedOutputStream os = new PipedOutputStream();
    PipedInputStream is = new PipedInputStream(os);

    System.setProperty("org.apache.pdfbox.baseParser.pushBackSize", "2024768"); //for large files

    PDDocument doc = PDDocument.load(dataStream, true);

    if (doc.isEncrypted()) { //remove the security before adding protections
        doc.decrypt("");
        doc.setAllSecurityToBeRemoved(true);
    }
    doc.save(os);
    doc.close();
    dataStream.close();
    os.close();
    return is;
}

Now take that returned InputStream and use it for your security application;

   PipedOutputStream os = new PipedOutputStream();
   PipedInputStream is = new PipedInputStream(os);

   System.setProperty("org.apache.pdfbox.baseParser.pushBackSize", "2024768");
   InputStream dataStream = secureData.data();

   PDDocument doc = PDDocument.load(dataStream, true);
   AccessPermission ap = new AccessPermission();
   //add what ever perms you need blah blah...
   ap.setCanModify(false);
   ap.setCanExtractContent(false);
   ap.setCanPrint(false);
   ap.setCanPrintDegraded(false);
   ap.setReadOnly();

   StandardProtectionPolicy spp = new StandardProtectionPolicy(UUID.randomUUID().toString(), "", ap);

   doc.protect(spp);

   doc.save(os);
   doc.close();
   dataStream.close();
   os.close();

Now this should return a proper document with no blank output!

Trick is to remove encryption first!

Answer from NightWolf on Stack Overflow
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › security › security-developer-guide.pdf pdf
Java Platform, Standard Edition Security Developer’s Guide Release 11 E94828-33
Security Properties. You may set ... Copyright © 1993, 2026, Oracle and/or its affiliates. ... Configuration. ... Tools Reference. ... Tools Reference. ... Copyright © 1993, 2026, Oracle and/or its affiliates. ... Elliptic Curve Diffie-Hellman (ECDH) key agreement algorithms. Most of the built-in providers ... Microsoft CryptoAPI. This provider, named SunMSCAPI, allows Java applications to seamlessly
🌐
The Swiss Bay
theswissbay.ch › pdf › Gentoomen Library › Programming › Java › O'Reilly - Java Security 2Ed.pdf pdf
Safari | Java Security, 2nd Edition -> Preface
1.1 What Is Security?...............................................................................................................................7 · 1.2 Software Used in This Book..............................................................................................................9 · 1.3 The Java Sandbox............................................................................................................................14
Discussions

java - Protecting PDF using PDFBox - Stack Overflow
Im really struggling with the documentation for PDFBox. For such a popular library info seems to be a little thin on the ground (for me!). Anyway the problem Im having relates to protecting the PD... More on stackoverflow.com
🌐 stackoverflow.com
java - How to check pdf file is password protected? - Stack Overflow
How to check pdf file is password protected or not in java? I know of several tools/libraries that can do this but I want to know if this is possible with just program in java. More on stackoverflow.com
🌐 stackoverflow.com
Java script embedded in pdf file
We cannot comment on this without knowing what kind of JavaScript code is embedded in the PDF. In general, it's recommended to use a PDF viewer that cannot execute JavaScript code unless you actually need it. SumatraPDF is a great open source option for this on Windows. More on reddit.com
🌐 r/cybersecurity_help
7
0
August 5, 2025
java - How to password protect a existing pdf file using java8 & iText? - Stack Overflow
I am using the spring boot project to implement my code with the following dependencies : com.itextpdf it... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Kiuwan
kiuwan.com › wp-content › uploads › 2024 › 05 › Security-Guide-for-Java-Developers.pdf pdf
A Security Guide for Java Developers
Java language. The guide highlights specific risks Java developers face and demonstrates what · proactive steps can be taken to protect these applications. This guide will explore the following topics ... There are several well-known security vulnerabilities in the Java programming language.
🌐
Acsac
acsac.org › 2009 › program › keynotes › gong.pdf pdf
Java Security: A Ten Year Retrospective Li Gong Mozilla Online Ltd
as all the Java APIs and libraries. The initial release was JDK · 1.0. Each subsequent major release, such as JDK 1.1 and · JDK 1.2, included major new features, while minor releases · such as JDK 1.1.2 and JDK 1.2.3 would include only bug ... As for security, JDK 1.0 has a clear-cut, binary model.
🌐
Karel++
csis.pace.edu › ~lchen › sweet › modules › 8-JavaSecurity.pdf pdf
Secure Web Development Teaching Modules1 Introduction to Java Security
Protecting confidential data is a very important task of computer security. Most of the labs in this tutorial · focus on identity authentication and data validation and they don’t encode/decode the data files. In this · lab you will try out Prof. Lixin Tao’s implementation of the Simplified DES algorithm described in file · “JavaSecurityLab/cipher-des/C-SDES.pdf”. This implementation aims at helping students understand the
🌐
Universiteit Twente
utwente.nl › en › eemcs › fmt › education › course-files › m2-software-systems › s-05-java-security.pdf pdf
Java & security Topic of Software Systems (TCS module 2)
JAVA’S SECURITY ADVANTAGES · (COMPARED TO C) Less susceptible to buffer overflows · This could happen in C: No pointer arithmetic in Java · variable a · variable b · 6 · TOP 25 MOST DANGEROUS · SOFTWARE WEAKNESSES · http://cwe.mitre.org/top25/ 7 ·
Find elsewhere
🌐
Università di Napoli Federico II
wpage.unina.it › pieroandrea.bonatti › didattica › security › java-security › Java_security.pdf pdf
Java security (in a nutshell)
Index of /pieroandrea.bonatti/didattica/security/java-security · Apache/2.4.7 (Ubuntu) Server at wpage.unina.it Port 80
🌐
Ucr
mirage.cs.ucr.edu › mobilecode › resources_files › IeeeMicro97.pdf pdf
JAVA SECURITY: PRESENT AND NEAR FUTURE
erence implementation in Java, which is typically shipped · together with the high-level APIs. Developers can use this ... Secure communication.
🌐
DZone
dzone.com › coding › java › how to password protect a pdf file using java: a step-by-step guide
How to Password Protect a PDF File Using Java
October 11, 2023 - With Java and the Apache PDFBox library, you can easily implement robust password protection for your PDF documents. This step-by-step guide has shown you how to load a PDF file, create a password protection policy, apply it, and save the ...
Top answer
1 of 1
12

I found the solution to this problem. It would appear that if the PDF comes from an external source, sometimes the PDF is protected or encrypted.

If you get a blank output when loading up a PDF document from an external source and add protections you are probably working with an encrypted document. I have a stream processing system working on PDF documents. So the following code works for me. If you are just working with PDF inputs then you could integrate the below code with your flow.

public InputStream convertDocument(InputStream dataStream) throws Exception {
    // just acts as a pass through since already in pdf format
    PipedOutputStream os = new PipedOutputStream();
    PipedInputStream is = new PipedInputStream(os);

    System.setProperty("org.apache.pdfbox.baseParser.pushBackSize", "2024768"); //for large files

    PDDocument doc = PDDocument.load(dataStream, true);

    if (doc.isEncrypted()) { //remove the security before adding protections
        doc.decrypt("");
        doc.setAllSecurityToBeRemoved(true);
    }
    doc.save(os);
    doc.close();
    dataStream.close();
    os.close();
    return is;
}

Now take that returned InputStream and use it for your security application;

   PipedOutputStream os = new PipedOutputStream();
   PipedInputStream is = new PipedInputStream(os);

   System.setProperty("org.apache.pdfbox.baseParser.pushBackSize", "2024768");
   InputStream dataStream = secureData.data();

   PDDocument doc = PDDocument.load(dataStream, true);
   AccessPermission ap = new AccessPermission();
   //add what ever perms you need blah blah...
   ap.setCanModify(false);
   ap.setCanExtractContent(false);
   ap.setCanPrint(false);
   ap.setCanPrintDegraded(false);
   ap.setReadOnly();

   StandardProtectionPolicy spp = new StandardProtectionPolicy(UUID.randomUUID().toString(), "", ap);

   doc.protect(spp);

   doc.save(os);
   doc.close();
   dataStream.close();
   os.close();

Now this should return a proper document with no blank output!

Trick is to remove encryption first!

🌐
IronPDF
ironpdf.com › ironpdf for java › blog › using ironpdf for java › password protect pdf in javaa
How to Password Protect PDF in Java
July 29, 2025 - Using IronPDF, you can restrict printing of a PDF by configuring the SecurityOptions class. Set the appropriate permissions to disallow actions like printing, then apply these settings to your PdfDocument object. To open an encrypted PDF in Java using IronPDF, use the PdfDocument.fromFile method, providing the file path and the password as parameters to decrypt and access the document.
🌐
nsoftware
nsoftware.com › securepdf
Secure PDF | PDF Security & PAdES Development Library | nsoftware
C++ Builder, Delphi, Java, JavaScript, ... choose /n software components. Download · Secure PDF includes everything needed to add PDF Signing and Encryption to any application - on any platform or development technology....
Rating: 4.9 ​ - ​ 74 votes
🌐
GeeksforGeeks
geeksforgeeks.org › java › encrypt-pdf-using-java
Encrypt PDF using Java - GeeksforGeeks
July 13, 2022 - We can encrypt any PDF using Java by using the external library PDFBox.
Top answer
1 of 6
4

Update

As per mkl's comment below this answer, it seems that there are two types of PDF structures permitted by the specs: (1) Cross-referenced tables (2) Cross-referenced Streams. The following solution only addresses the first type of structure. This answer needs to be updated to address the second type.

====

All of the answers provided above refer to some third party libraries which is what the OP is already aware of. The OP is asking for native Java approach. My answer is yes, you can do it but it will require a lot of work.

It will require a two step process:

Step 1: Figure out if the PDF is encrypted

As per Adobe's PDF 1.7 specs (page number 97 and 115), if the trailer record contains the key "\Encrypted", the pdf is encrypted (the encryption could be simple password protection or RC4 or AES or some custom encryption). Here's a sample code:

    Boolean isEncrypted = Boolean.FALSE;
    try {
        byte[] byteArray = Files.readAllBytes(Paths.get("Resources/1.pdf"));
        //Convert the binary bytes to String. Caution, it can result in loss of data. But for our purposes, we are simply interested in the String portion of the binary pdf data. So we should be fine.
        String pdfContent = new String(byteArray);
        int lastTrailerIndex = pdfContent.lastIndexOf("trailer");
        if(lastTrailerIndex >= 0 && lastTrailerIndex < pdfContent.length()) {
            String newString =  pdfContent.substring(lastTrailerIndex, pdfContent.length());
            int firstEOFIndex = newString.indexOf("%%EOF");
            String trailer = newString.substring(0, firstEOFIndex);
            if(trailer.contains("/Encrypt"))
                isEncrypted = Boolean.TRUE;
        }
    }
    catch(Exception e) {
        System.out.println(e);
        //Do nothing
    }

Step 2: Figure out the encryption type

This step is more complex. I don't have a code sample yet. But here is the algorithm:

  1. Read the value of the key "/Encrypt" from the trailer as read in the step 1 above. E.g. the value is 288 0 R.
  2. Look for the bytes "288 0 obj". This is the location of the "encryption dictionary" object in the document. This object boundary ends at the string "endobj".
  3. Look for the key "/Filter" in this object. The "Filter" is the one that identifies the document's security handler. If the value of the "/Filter" is "/Standard", the document uses the built-in password-based security handler.

If you just want to know whether the PDF is encrypted without worrying about whether the encryption is in form of owner / user password or some advance algorithms, you don't need the step 2 above.

Hope this helps.

2 of 6
3

you can use PDFBox:

http://pdfbox.apache.org/

code example :

try
{
    document = PDDocument.load( yourPDFfile );

    if( document.isEncrypted() )
    {
      //ITS ENCRYPTED!
    }
}

using maven?

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0</version>
</dependency>
🌐
Aspose Pty. Ltd.
tutorials.aspose.com › aspose.pdf › java › security permissions
PDF Security and Permissions Tutorials for Aspose.PDF Java | High Code APIs & Free Apps for Microsoft Word Document Manipulation
December 15, 2025 - These step-by-step guides teach you how to implement password protection, apply digital signatures, configure document permissions, redact sensitive content, and programmatically control access to your PDF files. Each tutorial includes complete Java code examples for common security scenarios, helping you build applications that maintain document confidentiality and integrity.
🌐
Reddit
reddit.com › r/cybersecurity_help › java script embedded in pdf file
r/cybersecurity_help on Reddit: Java script embedded in pdf file
August 5, 2025 -

So I downloaded this pdf file , I checked with kaspersky and it detected there is no threat and I also checked with virustotal and there was no threat detected;however, when I used cape sandbox it showed that the pdf gave 1 low IDS rule, is this pdf considered dangerous ? Thanks in advance

Top answer
1 of 2
5
We cannot comment on this without knowing what kind of JavaScript code is embedded in the PDF. In general, it's recommended to use a PDF viewer that cannot execute JavaScript code unless you actually need it. SumatraPDF is a great open source option for this on Windows.
2 of 2
1
SAFETY NOTICE: Reddit does not protect you from scammers. By posting on this subreddit asking for help, you may be targeted by scammers ( example? ). Here's how to stay safe: Never accept chat requests, private messages, invitations to chatrooms, encouragement to contact any person or group off Reddit, or emails from anyone for any reason. Moderators, moderation bots, and trusted community members cannot protect you outside of the comment section of your post. Report any chat requests or messages you get in relation to your question on this subreddit ( how to report chats? how to report messages? how to report comments? ). Immediately report anyone promoting paid services (theirs or their "friend's" or so on) or soliciting any kind of payment. All assistance offered on this subreddit is 100% free, with absolutely no strings attached. Anyone violating this is either a scammer or an advertiser (the latter of which is also forbidden on this subreddit). Good security is not a matter of 'paying enough.' Never divulge secrets, passwords, recovery phrases, keys, or personal information to anyone for any reason. Answering cybersecurity questions and resolving cybersecurity concerns never require you to give up your own privacy or security. Community volunteers will comment on your post to assist. In the meantime, be sure your post follows the posting guide and includes all relevant information, and familiarize yourself with online scams using r/scams wiki . I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
Stack Overflow
stackoverflow.com › questions › 71252990 › how-to-password-protect-a-existing-pdf-file-using-java8-itext
java - How to password protect a existing pdf file using java8 & iText? - Stack Overflow
I want my existing pdf to only be made password protected without using a new pdf at a specific path. ... package com.example.encryptMyPdf; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; import com.itextpdf.text.pdf.PdfWriter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class EncryptMyPdfApplication{ public static v
🌐
iText
itextpdf.com › solutions › pdf-security
PDF Security | iText PDF
March 17, 2020 - There are some great, simple ways to protect and secure your data with iText. Choose one for simple security, or a combination to meet your needs. We offer PDF Protector, a FREE online tool to evaluate how iText can help add protection to your workflow.