푸터 콘텐츠로 바로가기
JAVA용 IRONPDF 사용

Java에서 PDF를 암호로 보호하는 방법

This article will demonstrate how to use IronPDF to work with PDF documents and also protect new files with a user password.

IronPDF - Java PDF Library

IroqPDF Java PDF Library is a Java library for working with PDF documents. It provides a wide range of features for generating and manipulating PDFs, including the ability to add text, images, and other types of content, and control the layout and formatting of the document. It also provides a number of important features for securing PDF content, such as using password protection features in IronPDF.

Steps to Protect PDF using Password in Java Applications

Prerequisites for Project Setup

To use IronPDF to work with PDFs in a Java Maven project, you will need to make sure that you have the following prerequisites:

  1. Java Development Kit (JDK): A running current version of Java must be installed on your computer. If you don't have JAR files, then download the latest JDK from the Oracle website.
  2. Maven: Maven is an important build automation tool for Java projects which is required to manage the project and its dependencies. Download Maven or JAR file from the Apache Maven website if you don't have it installed.
  3. IronPDF for Java Library: You will also require the IronPDF for Java library, which will be added to your Maven project as a dependency. This can be done by adding the following dependency to your project's pom.xml file. Maven will automatically download and install it in the project.

    <dependency>
        <groupId>com.ironsoftware</groupId>
        <artifactId>ironpdf</artifactId>
        <version>YOUR_VERSION_HERE</version>
    </dependency>
    <dependency>
        <groupId>com.ironsoftware</groupId>
        <artifactId>ironpdf</artifactId>
        <version>YOUR_VERSION_HERE</version>
    </dependency>
    XML
  4. Slf4j Dependency: Add the Slf4j dependency in the pom.xml file.

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>2.0.3</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>2.0.3</version>
    </dependency>
    XML

Once you have set up your Java program with password protection capability for PDFs, you are ready to use IronPDF to protect a PDF file with password protection.

Important Steps Before Writing Code

First, import the necessary IronPDF classes into your Java code. Add the following code at the top of the "Main.java" file:

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.metadata.MetadataManager;
import com.ironsoftware.ironpdf.security.PdfPrintSecurity;
import com.ironsoftware.ironpdf.security.SecurityManager;
import com.ironsoftware.ironpdf.security.SecurityOptions;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.Date;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.metadata.MetadataManager;
import com.ironsoftware.ironpdf.security.PdfPrintSecurity;
import com.ironsoftware.ironpdf.security.SecurityManager;
import com.ironsoftware.ironpdf.security.SecurityOptions;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.Date;
JAVA

Now, in the main method, enter your license key using the IronPDF setLicenseKey method.

// Set your IronPDF license key
License.setLicenseKey("Your license key");
// Set your IronPDF license key
License.setLicenseKey("Your license key");
JAVA

Open an Encrypted PDF Document

The following code snippet will open a document that was encrypted with the password "password":

// Load an encrypted PDF file using its password
PdfDocument pdf = PdfDocument.fromFile(Paths.get("encrypted.pdf"), "secretPassword");
// Load an encrypted PDF file using its password
PdfDocument pdf = PdfDocument.fromFile(Paths.get("encrypted.pdf"), "secretPassword");
JAVA

In the above code snippet, an encrypted PDF file is opened with the password "password".

How to Password Protect PDF in Java, Figure 1: Opening an Encrypted PDF document Opening an Encrypted PDF document

Encrypt PDF Document using Password Protection

Let's change the owner password of the "encrypted.pdf" file, which was opened in the previous step. The following code helps to achieve this task:

// Change or set the document owner password
SecurityManager securityManager = pdf.getSecurity();
// Remove existing passwords and encryption from the document
securityManager.removePasswordsAndEncryption();
// Set a new password for the document
securityManager.setPassword("secret-key");
// Change or set the document owner password
SecurityManager securityManager = pdf.getSecurity();
// Remove existing passwords and encryption from the document
securityManager.removePasswordsAndEncryption();
// Set a new password for the document
securityManager.setPassword("secret-key");
JAVA

The first step is to remove the password using the removePasswordsAndEncryption method, and then set a new password using the setPassword method.

Save Password Protected PDF Documents

Finally, save the PDF document with the following line of code:

// Save the secured PDF document
pdf.saveAs(Paths.get("assets/secured.pdf"));
// Save the secured PDF document
pdf.saveAs(Paths.get("assets/secured.pdf"));
JAVA

The output file is now opened with the "secret-key" password.

How to Password Protect PDF in Java, Figure 2: Newly-encrypted PDF Document Newly-encrypted PDF Document

Edit File Security Settings

Important security options can be set easily with IronPDF in Java using the SecurityOptions class. The code below makes the PDF read-only and disallows users from copying, pasting, and printing, and sets passwords for the owner and user.

// Configure security options for the PDF document
SecurityOptions securityOptions = new SecurityOptions();
securityOptions.setAllowUserCopyPasteContent(false);
securityOptions.setAllowUserAnnotations(false);
securityOptions.setAllowUserPrinting(PdfPrintSecurity.NO_PRINT);
securityOptions.setAllowUserFormData(false);

SecurityManager securityManager = pdf.getSecurity();
// Apply the specified security options to the PDF
securityManager.setSecurityOptions(securityOptions);
// Configure security options for the PDF document
SecurityOptions securityOptions = new SecurityOptions();
securityOptions.setAllowUserCopyPasteContent(false);
securityOptions.setAllowUserAnnotations(false);
securityOptions.setAllowUserPrinting(PdfPrintSecurity.NO_PRINT);
securityOptions.setAllowUserFormData(false);

SecurityManager securityManager = pdf.getSecurity();
// Apply the specified security options to the PDF
securityManager.setSecurityOptions(securityOptions);
JAVA

This will set all the necessary security options for the PDF document.

How to Password Protect PDF in Java, Figure 3: New PDF Security Settings New PDF Security Settings

Summary

This article explained how to open an existing PDF document and add password protection using the IronPDF Library for Java in Java. IronPDF makes it a lot easier to work with PDF files in Java. Whether you want to create a new document or make a PDF viewer, IronPDF helps to achieve this task with a single line of code. IronPDF's Engine is well suited for the Java programming language, as it is fast and memory efficient. With IronPDF, you can set a user password along with the owner password. It provides full protection options along with other features like converting to PDF from other formats with IronPDF, splitting documents with IronPDF, and merging documents with IronPDF.

IronPDF can be used for free in a free trial of IronPDF and can be licensed for commercial use with IronPDF. Its lite package starts from $799. Download IronPDF and give it a try.

자주 묻는 질문

Java에서 PDF 문서를 비밀번호로 보호하려면 어떻게 해야 하나요?

Java에서 PDF 문서를 비밀번호로 보호하려면 IronPDF의 SecurityManager 클래스를 사용하여 사용자 비밀번호를 설정할 수 있습니다. 여기에는 PdfDocument 객체를 초기화하고, setPassword를 사용하여 원하는 비밀번호를 설정한 다음, saveAs 메서드를 사용하여 파일을 저장하는 것이 포함됩니다.

Java에서 PDF 프로젝트를 설정하려면 무엇이 필요하나요?

Java에서 IronPDF를 사용하여 PDF 프로젝트를 설정하려면 종속성 관리를 위한 Java 개발 키트(JDK), Maven이 필요하며 프로젝트의 pom.xml 파일에 IronPDF 라이브러리를 포함시켜야 합니다.

Java에서 PDF 파일을 어떻게 조작하나요?

IronPDF를 사용하면 PdfDocument와 같은 필요한 클래스를 가져와서 Java에서 PDF 파일을 조작할 수 있습니다. 이를 통해 콘텐츠를 편집하고, 문서를 병합하고, SecurityOptions 클래스를 사용하여 보안 설정을 적용할 수 있습니다.

Java를 사용하여 PDF를 인쇄하지 못하도록 제한하려면 어떻게 해야 하나요?

IronPDF를 사용하면 SecurityOptions 클래스를 구성하여 PDF의 인쇄를 제한할 수 있습니다. 인쇄와 같은 작업을 허용하지 않도록 적절한 권한을 설정한 다음 이러한 설정을 PdfDocument 개체에 적용하세요.

Java에서 암호화된 PDF를 여는 단계는 무엇인가요?

IronPDF를 사용하여 Java에서 암호화된 PDF를 열려면 파일 경로와 비밀번호를 매개변수로 제공하여 문서의 암호를 해독하고 액세스하는 PdfDocument.fromFile 메서드를 사용하세요.

Java용 PDF 라이브러리의 무료 버전이 있나요?

IronPDF는 개발자가 기능을 살펴보는 데 사용할 수 있는 무료 평가판을 제공합니다. 확장 사용 또는 상업용 프로젝트의 경우 라이선스 버전을 사용할 수 있습니다.

Java로 된 기존 PDF의 비밀번호를 변경하려면 어떻게 해야 하나요?

IronPDF를 사용하여 기존 PDF의 비밀번호를 변경하려면 현재 비밀번호로 문서를 열고 보안 관리자를 사용하여 비밀번호를 제거한 후 문서를 저장하기 전에 새 비밀번호를 설정하세요.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.