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

Java PDF 스탬퍼(초보자 튜토리얼)

IronPDF - Java PDF Library

IronPDF is a Java PDF Library for generating, reading, and editing PDF documents. It allows users to work with PDF documents with ease and accuracy. IronPDF for Java is built on the success of IronPDF for .NET and provides efficiency across different platforms. IronPDF for Java uses IronPdfEngine, which is fast and optimized for performance.

IronPDF helps extract text and images from PDFs and other objects from PDF files. It helps create PDFs from HTML String, URL, and images. It also allows conversion between different file formats. You can easily add new content and add digital signatures to PDFs along with document metadata to existing PDF documents. It is designed especially for Java 8+, Scala, and Kotlin, on any Windows, Linux, and Cloud platforms.

Steps to Create PDF Stamper using IronPDF in Java Application

Prerequisites

To make a PDF Stamper, you will need the following prerequisites:

1. Java IDE

You can use any Java-supported IDE. There are a bunch of IDEs available for Java development. This demonstration will be using IntelliJ IDE. You can use NetBeans, Eclipse, etc.

2. Maven Project

Maven is a dependency manager and allows control over the Java project. Maven for Java can be downloaded from the official Maven website. IntelliJ IDE for Java contains Maven support.

3. IronPDF

You can download and install IronPDF for Java in multiple ways.

  • Adding IronPDF dependency in the pom.xml file in the Maven project.
<dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf</artifactId>
    <version>LATEST_VERSION</version> 
</dependency>
<dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf</artifactId>
    <version>LATEST_VERSION</version> 
</dependency>
XML

4. Slf4j

This dependency is also required to stamp content on an existing PDF document. It can be added using the Maven dependencies manager in IntelliJ or directly downloaded from the Maven website. Add the following dependency to the pom.xml file:

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

Adding Necessary Imports

Once all the prerequisites are installed, the next step is to import the necessary IronPDF packages to work with PDF documents. Add the following code on top of the Main.java file:

import com.ironsoftware.ironpdf.License;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
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 com.ironsoftware.ironpdf.stamp.*;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.Date;
import com.ironsoftware.ironpdf.License;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
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 com.ironsoftware.ironpdf.stamp.*;

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

License Key

Some methods available in IronPDF require a license to be used. You can purchase a license or try IronPDF for free with a trial license. You can set the key as follows:

// Set the IronPDF license key
License.setLicenseKey("YOUR-KEY");
// Set the IronPDF license key
License.setLicenseKey("YOUR-KEY");
JAVA

Open an Existing PDF Document

To import an existing document for stamping new content, PdfDocument class is used. Its static fromFile method is used to load a file from a specific path with the actual file name. The code goes as follows:

// Load an existing PDF document
PdfDocument pd = PdfDocument.fromFile(Paths.get("sample.pdf"));
// Load an existing PDF document
PdfDocument pd = PdfDocument.fromFile(Paths.get("sample.pdf"));
JAVA

Loaded original document:

Java PDF Stamper (Beginner Tutorial), Figure 1: The sample document
The sample document

Add New HTML Content

IronPDF provides a stamp package. It allows a bunch of useful stamping options like BarcodeStamper, HtmlStamper, ImageStamper, TextStamper, and others for content alignment. To add new HTML content to this PDF document HtmlStamper class will be used. Let's use the file in the previous section and add some content to it. The following code helps to achieve this task:

// Create an HtmlStamper and set its content
HtmlStamper htmlStamper = new HtmlStamper();
htmlStamper.setHtml("New content added!");
// Create an HtmlStamper and set its content
HtmlStamper htmlStamper = new HtmlStamper();
htmlStamper.setHtml("New content added!");
JAVA

A HtmlStamper object is created and then used its setHtml method to attach new HTML code. The next step is to apply it to the existing PDF document to create a new PDF version.

Adding all the Interactive Elements to PDF Document

Using the PdfDocument object created earlier to add the HTML code to the existing document. It provides applyStamp with two overloads, one that accepts only the content as a Stamper object and the other with page selection as well.

// Apply the stamper to the PDF document
pd.applyStamp(htmlStamper);
// Apply the stamper to the PDF document
pd.applyStamp(htmlStamper);
JAVA

This will add the string description to the existing document.

Saving the Changes to the PDF

To save the file, use the saveAs method of the PdfDocument object.

// Save the modified PDF document
pd.saveAs("stamped.pdf");
// Save the modified PDF document
pd.saveAs("stamped.pdf");
JAVA

Java PDF Stamper (Beginner Tutorial), Figure 2: The stamped PDF file
The stamped PDF file

The HTML string is added to every page of the PDF document and at the middle of every page.

Stamp to Specific Pages

You can use another overload of the applyStamp method to add the content to a specific page.

// Stamp content to a specific page
pd.applyStamp(htmlStamper, PageSelection.singlePage(1));
// Stamp content to a specific page
pd.applyStamp(htmlStamper, PageSelection.singlePage(1));
JAVA

PageSelection class provides different methods to control the page number. firstPage, lastPage, allPages, and pageRange are some methods available to add the content appropriately.

Aligning the Content

You can use setVerticalAlignment, setHorizontalAlignment, setWidth, setHeight methods in each Stamper class to adjust the position of the content added to the existing PDF document. The following example code will help to place the text at the bottom left of the page:

// Set the alignment of the stamper
htmlStamper.setHorizontalAlignment(HorizontalAlignment.LEFT);
htmlStamper.setVerticalAlignment(VerticalAlignment.BOTTOM);
// Set the alignment of the stamper
htmlStamper.setHorizontalAlignment(HorizontalAlignment.LEFT);
htmlStamper.setVerticalAlignment(VerticalAlignment.BOTTOM);
JAVA

Java PDF Stamper (Beginner Tutorial), Figure 3: The output PDF file with stamper alignment
The output PDF file with stamper alignment

You can use setVerticalOffset, setHorizontalOffset method to further adjust the positioning of the content.

For more information on working with PDF files using IronPDF visit this code example for HTML to PDF conversion in Java.

Stamp Metadata, Signature, and Security Options to Existing Document

IronPDF for Java is a versatile library and provides the facility to add file descriptions in the form of metadata, user permissions, user password, add digital signature, and create signed documents to save the version of the PDF document.

Metadata

// Edit file metadata
MetadataManager metadata = pd.getMetadata();
metadata.setAuthor("Satoshi Nakamoto");
metadata.setKeywords("SEO, Friendly");
metadata.setModifiedDate(new Date().toString());
// Edit file metadata
MetadataManager metadata = pd.getMetadata();
metadata.setAuthor("Satoshi Nakamoto");
metadata.setKeywords("SEO, Friendly");
metadata.setModifiedDate(new Date().toString());
JAVA

Security Options

You can also control the security options of your PDF file so that data is saved from unauthorized use. It provides options to set setAllowUserPrinting, setAllowUserEdits, setAllowUserCopyPasteContent, setAllowUserAnnotations, setUserPassword, setAllowUserFormData parameters to true or false. The following sample code will help to set all the objects properties mentioned above.

// Edit file security settings
SecurityOptions securityOptions = new SecurityOptions();
securityOptions.setAllowUserCopyPasteContent(false);
securityOptions.setAllowUserAnnotations(false);
securityOptions.setAllowUserPrinting(PdfPrintSecurity.FULL_PRINT_RIGHTS);
securityOptions.setAllowUserFormData(false);
securityOptions.setOwnerPassword("top-secret");
securityOptions.setUserPassword("sharable");
// Edit file security settings
SecurityOptions securityOptions = new SecurityOptions();
securityOptions.setAllowUserCopyPasteContent(false);
securityOptions.setAllowUserAnnotations(false);
securityOptions.setAllowUserPrinting(PdfPrintSecurity.FULL_PRINT_RIGHTS);
securityOptions.setAllowUserFormData(false);
securityOptions.setOwnerPassword("top-secret");
securityOptions.setUserPassword("sharable");
JAVA

User Password

// Change or set the document encryption password
SecurityManager securityManager = pd.getSecurity();
securityManager.removePasswordsAndEncryption();
securityManager.makePdfDocumentReadOnly("secret-key");

securityManager.setSecurityOptions(securityOptions);
pd.saveAs(Paths.get("assets/secured.pdf"));
// Change or set the document encryption password
SecurityManager securityManager = pd.getSecurity();
securityManager.removePasswordsAndEncryption();
securityManager.makePdfDocumentReadOnly("secret-key");

securityManager.setSecurityOptions(securityOptions);
pd.saveAs(Paths.get("assets/secured.pdf"));
JAVA

For stamping digital signatures on the actual file, you can see this detailed code example for PDF signatures.

Summary

This article discussed how to stamp content on an existing PDF document in Java. There is a stamp package with a bunch of useful stamping classes, which can be used to add multiple format content to PDF at any desired location in the original document.

IronPDF is a versatile library as it can be seen from the above code examples as well. It is quite simple but yet a very powerful PDF generation and manipulation tool. This helps developers to easily integrate all PDF functionalities in a single Java application program.

IronPDF is free for single development and provides a free trial license without a watermark to test out its complete functionality. However, for commercial use, it should be licensed with IronPDF.

Lastly, IronPDF offers a special promotion to purchase Iron Software suites in which developers can buy all five Iron Software products for the price of two licenses.

자주 묻는 질문

Java로 된 기존 PDF 문서에 콘텐츠를 추가하려면 어떻게 해야 하나요?

Java용 IronPDF의 HtmlStamper 클래스를 사용하여 기존 PDF 문서에 HTML 콘텐츠를 추가할 수 있습니다. 이 클래스를 사용하면 원래 서식을 유지하면서 새 콘텐츠를 통합할 수 있습니다.

Java로 PDF 스탬퍼를 만드는 주요 단계는 무엇인가요?

Java용 IronPDF를 사용하여 PDF 스탬퍼를 만들려면 Java IDE를 설정하고 종속성 관리를 위한 Maven 프로젝트를 생성하고 IronPDF 라이브러리를 포함해야 합니다. 그런 다음 필요한 클래스를 가져오고, 라이선스를 초기화하고, 기존 PDF를 열고, HtmlStamper를 사용하여 콘텐츠를 추가합니다.

새 콘텐츠를 추가할 때 PDF의 서식이 유지되도록 하려면 어떻게 해야 하나요?

Java용 IronPDF는 새 콘텐츠를 추가할 때 PDF의 원래 서식을 유지합니다. 이는 새로운 요소를 통합하면서 기존 레이아웃을 정확하게 복제하는 강력한 렌더링 엔진을 통해 이루어집니다.

PDF의 특정 페이지에만 스탬프를 적용할 수 있나요?

예, Java용 IronPDF를 사용하면 applyStamp 메서드와 함께 PageSelection 클래스를 사용하여 PDF 내의 특정 페이지를 스탬핑 대상으로 지정할 수 있습니다.

PDF 문서에서 스탬프가 찍힌 콘텐츠의 위치를 조정하려면 어떻게 해야 하나요?

페이지에서 새 콘텐츠가 표시되는 위치를 제어하기 위해 HtmlStamper 클래스의 setVerticalAlignmentsetHorizontalAlignment 메서드를 사용하여 PDF에서 스탬프가 찍힌 콘텐츠의 위치를 조정할 수 있습니다.

PDF 문서에 사용할 수 있는 보안 기능은 무엇인가요?

Java용 IronPDF는 사용자 권한 설정, 비밀번호 추가, PDF 문서 내 콘텐츠 인쇄, 편집 및 복사에 대한 액세스 제어 등 여러 가지 보안 기능을 제공합니다.

상업적 목적으로 PDF 라이브러리를 사용하려면 라이선스가 필요하나요?

예, 상업적 환경에서 Java용 IronPDF를 사용하려면 상업용 라이선스가 필요합니다. 그러나 워터마크 없이 라이브러리의 전체 기능을 테스트할 수 있는 무료 평가판 라이선스를 사용할 수 있습니다.

Java용 IronPDF와 호환되는 플랫폼은 무엇인가요?

Java용 IronPDF는 Java 8+, Scala, Kotlin과 호환되며 Windows, Linux 및 클라우드 환경을 비롯한 다양한 플랫폼을 지원합니다.

HTML 콘텐츠를 Java에서 PDF로 변환하려면 어떻게 해야 하나요?

HTML 문자열이나 파일을 PDF 문서로 정확하게 렌더링할 수 있는 Java용 IronPDF의 RenderHtmlAsPdf 메서드를 사용하여 HTML 콘텐츠를 PDF로 변환할 수 있습니다.

프로젝트에서 Java용 IronPDF를 사용하려면 무엇이 필요하나요?

Java용 IronPDF를 사용하려면 IntelliJ와 같은 Java IDE, 종속성 관리를 위한 Maven 프로젝트 및 IronPDF 라이브러리가 있어야 합니다. 또한 관련 클래스를 가져오고 라이브러리에 대한 라이선스를 설정해야 합니다.

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

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

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