跳過到頁腳內容
使用 IRONPDF FOR JAVA

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

先決條件

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> <!-- Make sure to replace LATEST_VERSION with the actual version number -->
</dependency>
<dependency>
    <groupId>com.ironsoftware</groupId>
    <artifactId>ironpdf</artifactId>
    <version>LATEST_VERSION</version> <!-- Make sure to replace LATEST_VERSION with the actual version number -->
</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

添加必要的導入

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. 程式碼如下:

// 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.

總結

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文檔中添加內容?

您可以使用IronPDF for Java的HtmlStamper類向現有的PDF文檔中添加HTML內容。此類允許您在保留原始格式的同時集成新內容。

在Java中創建PDF蓋章器的主要步驟是什麼?

要使用IronPDF for Java創建PDF蓋章器,您需要設置Java IDE,創建用于依賴項管理的Maven項目,並包括IronPDF庫。然後,導入必要的類,初始化許可證,打開現有的PDF,並使用HtmlStamper添加內容。

如何確保在添加新內容時保留PDF的格式?

在使用IronPDF for Java添加新內容時,IronPDF保持了PDF的原始格式。這是通過其強大的渲染引擎實現的,該引擎能夠精準地復制現有佈局同時集成新元素。

是否可以僅向PDF的某些頁面應用蓋章?

可以,使用IronPDF for Java,您可以將applyStamp方法與PageSelection類一起使用,以針對PDF中的特定頁面進行蓋章。

我該如何調整PDF文檔中蓋章內容的位置?

您可以通過使用HtmlStamper類中的setVerticalAlignmentsetHorizontalAlignment方法調整PDF中蓋章內容的位置,以控制新內容在頁面上的顯示位置。

PDF文檔可用的安全功能有哪些?

IronPDF for Java提供了多種安全功能,包括設置用戶權限、添加密碼以及控制打印、編輯和複製PDF文檔內容的訪問。

使用PDF庫進行商業用途是否需要許可證?

是的,在商業環境中使用IronPDF for Java需要商業許可證。然而,可以獲得免費試用許可證以測試庫的全部功能而不帶水印。

IronPDF for Java兼容哪些平台?

IronPDF for Java兼容Java 8+、Scala、Kotlin,並支持包括Windows、Linux和雲環境在內的多個平台。

如何在Java中將HTML內容轉換為PDF?

您可以使用IronPDF for Java的RenderHtmlAsPdf方法將HTML內容轉換為PDF,允許HTML字符串或文件準確地渲染為PDF文檔。

項目中使用IronPDF for Java需要哪些準備?

要開始使用IronPDF for Java,請確保您擁有IntelliJ等Java IDE、一個用於管理依賴項的Maven項目,以及IronPDF庫。您還需要導入相關類並設置庫的許可證。

Darrius Serrant
全棧軟件工程師 (WebOps)

Darrius Serrant 擁有邁阿密大學計算機科學學士學位,目前任職於 Iron Software 的全栈 WebOps 市場營銷工程師。從小就迷上編碼,他認為計算既神秘又可接近,是創意和解決問題的完美媒介。

在 Iron Software,Darrius 喜歡創造新事物,並簡化複雜概念以便於理解。作為我們的駐場開發者之一,他也自願教學生,分享他的專業知識給下一代。

對 Darrius 來說,工作令人滿意因為它被重視且有實際影響。