在 Java 中編輯 PDF (完整教程)

This article was translated from English: Does it need improvement?
Translated
View the article in English

本教程概述了 Java 開發人員如何使用 IronPDF 編輯現有 PDF 文件的內容和結構。這包括使用 IronPDF 的 HTML 轉換功能從 HTML 渲染的 PDF 文件,以及使用其他第三方應用程式和軟體庫生成的 PDF。

教程สำหรับ 在C#.NET和VB.NET中編輯PDF文件 is also available.*

本教程假設讀者已經知道如何使用IronPDF來 將HTML內容轉換為PDFs. 如果您不熟悉此功能,請先閱讀 HTML 轉 PDF 教程,然後再繼續本教程 (或需要重新了解基本工作流程).


目錄

  • 編輯文件結構

    • 操作 PDF 文件

    • 增加、複製和刪除頁面

    • 合併和拆分 PDF

    • 設定 PDF 文件的自訂大小

    • 設定 PDF 方向
  • 設定 PDF 的自訂邊距
  • 將 PDF 文件轉換為圖像
  • 添加背景和前景

    • 添加 PDF 作為背景
  • 添加 PDF 作為前景
  • 圖像和文字提取

    • 提取內容
  • 提取圖像
  • 編輯文件屬性

    • 添加和使用 PDF 元數據

    • 數位簽名
  • 壓縮 PDF
  • 編輯 PDF 內容

    • 添加頁首和頁尾

    • 大綱和書籤

    • 添加和編輯註釋

    • 蓋章和加水印

    • 蓋章概覽

    • 蓋章範例

    • 將文字蓋章到 PDF 上

    • 將圖像蓋章到 PDF 上

    • 將條碼蓋章到 PDF 上

    • 將 QR Code 蓋章到 PDF 上
  • 添加水印到 PDF 上
  • 在 PDF 中使用表單

    • 創建和編輯表單
  • 填寫現有表單
  • 發送 PDF 以進行打印

入門

Java Maven 圖書館用於 PDF

安裝與 Maven

<dependency>
   <groupId>com.ironsoftware</groupId>
   <artifactId>ironpdf</artifactId>
   <version>2024.9.1</version>
</dependency>
Java PDF JAR

下載 JAR

  下載 JAR

手動安裝到您的項目中

在 Java 專案中整合 IronPDF 庫有兩種方式:

  1. 在使用 Maven 配置的 Java 專案中新增 IronPDF 為相依項目

  2. 下載 IronPDF JAR 檔案並手動新增到專案的類路徑中

要在 Java 專案中使用 Maven 安裝 IronPDF,請在 Java 專案的 pom.xml 檔案的相依項目部分中包含以下組件。

<dependency>
   <groupId>com.ironsoftware</groupId>
   <artifactId>com.ironsoftware</artifactId>
   <version>2024.9.1</version>
</dependency>

喜歡手動管理JAR文件的開發人員可以 下載 IronPDF 庫的 JAR 文件 並將其添加到他們的項目類路徑中。

直接從下載IronPDF JAR文件 這裡 (或從 Maven 倉庫).


教程內容

編輯文件結構

操作 PDF 文件

IronPDF 使管理 PDF 變得輕而易舉,其功能包括在特定索引處添加 PDF,按照範圍或單獨複製頁面,並輕鬆刪除頁面。所有這些任務都在後台無縫處理。

添加頁面

import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;

PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PdfDocument coverPagePdf = PdfDocument.renderHtmlAsPdf("<h1>Cover Page</h1><hr>");
PDF.prependPdf(coverPagePdf);
PDF.saveAs(Paths.get("report_with_cover.pdf"));
JAVA

複製頁面

import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;

PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PDF.copyPages(0,1).saveAs("report_highlight.pdf");
JAVA

刪除頁面

import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;

PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PDF.removePages(PageSelection.lastPage()).saveAs(Paths.get("assets/lastPageRemove.pdf"));
JAVA

附加封面頁

import com.ironsoftware.ironpdf.PdfDocument;  
import com.ironsoftware.ironpdf.headerfooter.HeaderFooterOptions;
import java.io.IOException;  
import java.nio.file.Paths;

// Create a Sample Cover Page using RenderHtmlAsPdf
PdfDocument coverPage = PdfDocument.renderHtmlAsPdf("<h1>This is a Cover Page</h1>");
PdfDocument webpage = PdfDocument.renderUrlAsPdf("https://www.nuget.org/packages/IronPdf/");

// Set the page number of the PDF document to be created to 2.
HeaderFooterOptions headerFooterOptions = new HeaderFooterOptions();
headerFooterOptions.setFirstPageNumber(1);
TextHeaderFooter footer = new TextHeaderFooter();
footer.setLeftText("");
footer.setCenterText("Page {page}");
footer.setRightText("");
webpage.addTextFooter(footer, headerFooterOptions);

// Convert a web page's content to a PDF document.
// Merge the cover page with the web page and save the new PDF to the filesystem.
try {
    PdfDocument.merge(coverPage, webpage).saveAs(Paths.get("assets/cover_page_pdf.pdf"));
} catch (IOException e) {
    throw new RuntimeException(e);
}
JAVA

了解更多關於 在 PDF 文件中附加封面.

合併和分割PDF文件

IronPDF Java 通過其用戶友好的 API 簡化了將多個 PDF 合併為一個或分割現有 PDF 的過程。

將多個現有的 PDF 文件合併成一個 PDF 文件

import com.ironsoftware.ironpdf.PdfDocument;  
import java.io.IOException;  
import java.nio.file.Paths;

String htmlA = "<p> [PDF_A] </p>"
        + "<p> [PDF_A] 1st Page </p>"
        + "<div style = 'page-break-after: always;' ></div>"
        + "<p> [PDF_A] 2nd Page</p>";
String htmlB = "<p> [PDF_B] </p>"
        + "<p> [PDF_B] 1st Page </p>"
        + "<div style = 'page-break-after: always;' ></div>"
        + "<p> [PDF_B] 2nd Page</p>";

PdfDocument pdfA = PdfDocument.renderHtmlAsPdf(htmlA);
PdfDocument pdfB = PdfDocument.renderHtmlAsPdf(htmlB);
PdfDocument merged = PdfDocument.merge(pdfA, pdfB);

merged.saveAs(Paths.get("assets/merged.pdf"));
JAVA

分割PDF並提取頁面

import com.ironsoftware.ironpdf.PdfDocument;  
import java.io.IOException;  
import java.nio.file.Paths;
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PdfDocument copied = PDF.copyPage(0);
copied.saveAs("assets/Split.pdf");
JAVA

設定PDF文件的自訂大小

IronPDF 使開發者能夠創建具有非標準尺寸的 PDF 文件,超越傳統的 A4 大小 (8½吋 x 11吋 或 21.59公分 x 27.94公分).

import com.ironsoftware.ironpdf.*;  
import com.ironsoftware.ironpdf.render.*;  
import java.io.IOException;  
import java.nio.file.Paths;

String html = "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>";  

ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();  
renderOptions.setPaperSize(PaperSize.Custom);  

/*  
 * Setting page sizes using different measuring units: 
 * 1. setCustomPaperWidth( width ) / setCustomPaperHeight( height ): for inches 
 * 2. setCustomPaperSizeInCentimeters( width, height ): for centimeters. 
 * 3. setCustomPaperSizeInMillimeters( width, height ): for millimeters 
 * 4. setCustomPaperSizeInPixelsOrPoints( width, height ): for pixels/points 
 */
renderOptions.setCustomPaperSizeInCentimeters(13.97, 13.97);  
PdfDocument.renderHtmlAsPdf(html, renderOptions).saveAs(Paths.get("assets/CustomPaperSize.pdf"));
JAVA

瞭解更多有關 PDFs的自訂大小.

設置PDF方向

IronPDF for Java允許修改新建和現有PDF的頁面方向。默認情況下,用IronPDF創建的新PDF設置為縱向,但開發人員可以在轉換內容時使用ChromePdfRenderOptions實例來更改方向。 (例如 HTML、RTFs 和 URLs) 轉換為 PDFs。

import com.ironsoftware.ironpdf.PdfDocument;  
import com.ironsoftware.ironpdf.edit.PageSelection;  
import com.ironsoftware.ironpdf.page.PageRotation;  
import com.ironsoftware.ironpdf.render.*;  
import java.io.IOException;  
import java.nio.file.Paths;

// Use the setPaperOrientation method to set rendered PDFs in portrait or landscape orientation.  
// Note: This will only work for newly-created PDFs!  
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();  
renderOptions.setPaperOrientation(PaperOrientation.LANDSCAPE);  
PdfDocument newPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com", renderOptions);  
newPdf.saveAs(Paths.get("assets/LandscapePdf.pdf"));  

// Use the rotatePage/rotateAllPages methods to adjust the page orientation for existing PDFs  
PdfDocument existingPdf = PdfDocument.fromFile(Paths.get("assets/example.pdf"));  

// Get the orientation of the first page of the existing PDF document.  
PageRotation firstPageRotation = existingPdf.getPagesInfo().get(0).getPageRotation();  
System.out.println(firstPageRotation);  

// Rotate the first page of the document only 90 degrees clockwise.  
existingPdf.rotatePage(PageRotation.CLOCKWISE_90, PageSelection.firstPage());  

// Rotate all pages of the document clockwise.  
existingPdf.rotateAllPages(PageRotation.CLOCKWISE_270);  

existingPdf.saveAs(Paths.get("assets/ExistingPdfRotated.pdf"));
JAVA

如果您想獲取更多資訊,可以訪問IronPDF的網站部分 設定 PDF 方向.

設定 PDF 的自訂邊距

IronPDF 在所有邊的預設邊距為 25 毫米 (上, 下, 左, 右)然而,開發人員可以使用 IronPDF 自訂每個邊距的具體尺寸以符合設計需求。

import com.ironsoftware.ironpdf.PdfDocument;  
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;  
import java.io.IOException;  
import java.nio.file.Paths;

// Set Margins (in millimeters)  
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();  
renderOptions.setMarginTop(40);  
renderOptions.setMarginLeft(20);  
renderOptions.setMarginRight(20);  
renderOptions.setMarginBottom(40);  

PdfDocument.renderHtmlFileAsPdf("assets/wikipedia.html", renderOptions).saveAs(Paths.get("assets/MyContent.pdf"));
JAVA

請訪問IronPDF網站以了解更多有關條件 為 PDF 文件設置自定義邊距.

將 PDF 文件轉換為圖片

IronPDF 可以將載入的 PDF 文件頁面、轉換的源內容或經過修改的 PDF(包括標題、頁腳、邊距等)導出為圖片,這些圖片可以保存到文件系統中,儲存在資料庫中,或通過網絡傳輸。

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.image.ToImageOptions;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;

PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/composite.pdf"));

// Extract all the pages from the PDF file.
List<BufferedImage> extractedImages = pdf.toBufferedImages();

// With the ToImageOptions object, specify maximum image dimensions for each
// extracted image, as well as their DPI
ToImageOptions rasterOptions = new ToImageOptions();
rasterOptions.setImageMaxHeight(100);
rasterOptions.setImageMaxWidth(100);

// Call the toBufferedImage method along with a PageSelection object to choose the pages from which to
// extract the images
//
// Available PageSelection methods include: allPages, lastPage, firstPage, singlePage(int pageIndex),
// and pageRange(int startingPage, int endingPage)
List<BufferedImage> sizedExtractedImages = pdf.toBufferedImages(rasterOptions, PageSelection.allPages());

// Save all the extracted images to a file location
int i = 1;
for (BufferedImage extractedImage : sizedExtractedImages) {
    String fileName = "assets/images/" + i++ + ".png";
    ImageIO.write(extractedImage, "PNG", new File(fileName));
}
JAVA

添加背景和前景

IronPDF 提供了 addBackgroundaddForeground 方法用于 將特定的背景或前景元素添加到 PDF這些方法使開發人員能夠將一個 PDF 的內容作為另一個 PDF 的背景或前景結合起來,從而有效地基於通用設計模板生成 PDF 集合。

將 PDF 添加為背景

import com.ironsoftware.ironpdf.*;  
import java.io.IOException;  
import java.nio.file.Paths;

// Load background PDFs from the filesystem (or create them programmatically)  
PdfDocument backgroundPdf = PdfDocument.fromFile(Paths.get("assets/MyBackground.pdf"));  

// Render content (HTML, URL, etc) as a PDF Document  
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://www.nuget.org/packages/IronPdf");  

// Add the background PDFs to the newly-rendered document.  
pdf.addBackgroundPdf(backgroundPdf);  

pdf.saveAs(Paths.get("assets/BackgroundPdf.pdf"));
JAVA

新增 PDF 作為前景

import com.ironsoftware.ironpdf.*;  
import java.io.IOException;  
import java.nio.file.Paths;

// Load foreground PDFs from the filesystem (or create them programmatically)  
PdfDocument foregroundPdf = PdfDocument.fromFile(Paths.get("assets/MyForeground.pdf"));  

// Render content (HTML, URL, etc) as a PDF Document  
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://www.nuget.org/packages/IronPdf");  

// Add the foreground PDFs to the newly-rendered document.  
pdf.addForegroundPdf(foregroundPdf);  

pdf.saveAs(Paths.get("assets/BackgroundForegroundPdf.pdf"));
JAVA

圖像和文本提取

IronPDF 的全面 PDF 創建和編輯功能包括能够 提取內容 使用其內容提取方法進行細粒度操作。

extractAllText 方法適用於所有 PdfDocument 對象,返回包含 PDF 文件中所有文本的字符串。此外,extractAllImages 返回 PDF 中所有嵌入圖像的集合,每個圖像都是 BufferedImage 對象。若要以原始字節形式檢索這些圖像,請使用 extractAllRawImages 方法。

提取內容

PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://unsplash.com/");
String text = pdf.extractAllText();
System.out.println("Text extracted from the website: " + text);
JAVA

提取圖像

PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://unsplash.com/");
try {
    List<BufferedImage> images = pdf.extractAllImages();
    System.out.println("Number of images extracted from the website: " + images.size());

    int i = 0;
    for (BufferedImage image : images) {
        ImageIO.write(image, "PNG", Files.newOutputStream(Path.of("assets/extracted_" + ++i + ".png")));
    }
} catch(Exception exception) {
    System.out.println("Failed to extract images from the website");
    exception.printStackTrace();
}
JAVA

編輯文件屬性

添加和使用 PDF 元數據

IronPDF 提供了 修改 PDF 中的元數據 包括安全功能,例如將 PDF 設為唯讀、無法列印、密碼保護和加密。在 IronPDF for Java 中,可以使用 MetadataManager 存取和編輯 PDF 的中繼資料。MetadataManager 類別提供直接存取中繼資料內容的功能,並允許開發人員透過具有相同名稱的 getter 和 setter 輕鬆讀取和編輯常見的中繼資料屬性。

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

// Open an encrypted file (or create a new one from HTML)
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/encrypted.pdf"), "password");

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

// Edit file security settings
// The code below makes the PDF read only and disallows users to copy, paste, and print
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");

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

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

數位簽章

IronPDF for Java 允許使用 .pfx.p12 格式的 X509Certificate2 數位證書對新的或現有的 PDF 文件進行安全簽章。透過數位簽章 PDF 文件,保證文件的真實性,並且在未經適當的證書驗證前不會被更改。這提高了文件的可靠性。

如果您正在尋找免費生成簽章證書的方法,Adobe Reader 可以滿足您的需求。只需按照以下的说明進行操作 Adobe 數位 ID 教程除了傳統的數位簽章過程外,IronPDF for Java 還提供了使用手寫簽名圖片或公司印章圖片來簽署 PDF 的選項。這讓企業更容易個性化他們的文件,並增加一層額外的安全性。

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.signature.Signature;
import com.ironsoftware.ironpdf.signature.SignatureManager;
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));

File path = new File("assets/Ironpdf.pfx");
byte [] certificate = new byte [(int)path.length()];

Signature signature = new Signature(certificate,"1234");

SignatureManager manager = PDF.getSignature();

manager.SignPdfWithSignature(signature);
JAVA

壓縮PDF

IronPDF 透過 PdfDocument 類中的 compressImages 方法來減小 PDF 檔案大小,使得壓縮包含大圖像的 PDF 變得容易。此優化可以在透過電子郵件和其他通訊渠道傳輸 PDF 時,顯著節省存儲空間和成本。

import com.ironsoftware.ironpdf.*;
import java.io.IOException;  
import java.nio.file.Paths;

PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/document.pdf"));  

// Valid image compression values range from 1 to 100, where 100 represents 100% of the  
// original image quality.  
pdf.compressImages(60);  
pdf.saveAs(Paths.get("assets/document_compressed.pdf"));  

// The second, optional parameter can scale down the image resolution according to its visible  
// size in the PDF document. Note that this may cause distortion with some image configurations  
pdf.compressImages(90, true);  
pdf.saveAs(Paths.get("assets/document_scaled_compressed.pdf"));
JAVA

編輯PDF內容

添加頁眉和頁腳

IronPDF 提供以下功能 添加自訂 HTML 頁首和頁尾 使用 ChromePdfRenderOptionsHtmlHeaderFooter 類別生成 PDF。IronPDF 能夠 自訂文字標頭和頁尾 可通過 TextHeaderFooter 類加入到 PDF 中,該類允許指定頁眉或頁腳左側、右側或中間區域的文本。這包括使用內建的模板標籤,如 {日期}, {時間},和 {頁面},或任何其他所需的自訂文本。

HTML 標頭和頁尾

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.headerfooter.HtmlHeaderFooter;
import java.io.IOException;
import java.nio.file.Paths;

PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
// Build a footer using HTML
// Merge Fields are: {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
HtmlHeaderFooter footer = new HtmlHeaderFooter();
footer.setMaxHeight(15); // millimeters
footer.setHtmlFragment("<center><i>{page} of {total-pages}</i></center>");
footer.setDrawDividerLine(true);
pdf.addHtmlFooter(footer);
List<PdfDocument> pdfs = new ArrayList<>();

// Build a header using an image asset
// Note the use of BaseUrl to set a relative path to the assets
HtmlHeaderFooter header = new HtmlHeaderFooter();
header.setMaxHeight(20); // millimeters
header.setHtmlFragment("<img src=\"logo.png\" />");
header.setBaseUrl("./assets/");
pdf.addHtmlHeader(header);
try {
    pdf.saveAs(Paths.get("assets/html_headers_footers.pdf"));
} catch (IOException e) {
    throw new RuntimeException(e);
}
JAVA

文本標頭和頁尾

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.font.FontTypes;
import com.ironsoftware.ironpdf.headerfooter.TextHeaderFooter;
import com.ironsoftware.ironpdf.headerfooter.HeaderFooterOptions;
import java.io.IOException;

// Initialize HeaderFooterOptions object.
HeaderFooterOptions options = new HeaderFooterOptions();
PdfDocument pdf = PdfDocument.renderUrlAsPdf("http://www.google.com");

// Add a header to every page easily
// Mergeable fields are:
// {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
options.setFirstPageNumber(1); // use 2 if a coverpage  will be appended
TextHeaderFooter textHeader = new TextHeaderFooter();
textHeader.setDrawDividerLine(true);
textHeader.setCenterText("{url}");
textHeader.setFont(FontTypes.getHelvetica());
textHeader.setFontSize(12);
pdf.addTextHeader(textHeader, options);

// Add a footer too
TextHeaderFooter textFooter = new TextHeaderFooter();
textFooter.setDrawDividerLine(true);
textFooter.setFont(FontTypes.getArial());
textFooter.setFontSize(10);
textFooter.setLeftText("{date} {time}");
textFooter.setRightText("{page} of {total-pages}");
pdf.addTextFooter(textFooter, options);

try {
    pdf.saveAs(Paths.get("assets/text_headers_footers.pdf"));
} catch (IOException e) {
    System.out.println("Failed to save PDF");
    throw new RuntimeException(e);
}
JAVA

大綱和書籤

使用 BookmarkManager,開發人員可以創建階層結構的 PDF中的書籤允許用戶輕鬆導航到文件的不同部分。要添加新的書籤,開發者可以使用 add 方法,指定書籤的標題和頁碼。書籤還可以嵌套在其他書籤內部,以創建更有組織結構。

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.bookmark.Bookmark;
import com.ironsoftware.ironpdf.bookmark.BookmarkManager;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;

// Load an existing PDF from the file system (or create a new one from HTML)
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/book.pdf"));

// Add top-level bookmarks to pages of the PDF using their page indices
BookmarkManager bookmarks = pdf.getBookmark();
bookmarks.addBookMarkAtEnd("Author's Note", 2);
bookmarks.addBookMarkAtEnd("Table of Contents", 3);
bookmarks.addBookMarkAtEnd("Summary", 10);
bookmarks.addBookMarkAtEnd("References", 12);

// Retrieve a reference to the Summary bookmark so that we can add a sublist of bookmarks to it.
List<Bookmark> bookmarkList = bookmarks.getBookmarks();
Bookmark bookmark = bookmarkList.get(2);
bookmark.AddChildBookmark("Conclusion", 11);

// Save the PDF to the filesystem
pdf.saveAs(Paths.get("assets/bookmarked.pdf"));
JAVA

添加和編輯註釋

IronPDF 允許添加「便條」風格 註釋到特定頁面 使用 AnnotationManagerAnnotationOptions 類來對 PDF 進行註解。開發人員可以通過提供文本來創建基於文本的註解,並且 (x,y) 將座標作為參數傳遞給 AnnotationOptions 構造函數,然後使用 AnnotationManageraddTextAnnotation 方法將註解添加到所需的頁面。

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.annotation.AnnotationIcon;
import com.ironsoftware.ironpdf.annotation.AnnotationManager;
import com.ironsoftware.ironpdf.annotation.AnnotationOptions;
import java.io.IOException;
import java.nio.file.Paths;

// Create a new PDF or load an existing one from the filesystem
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/example.pdf"));

// Create an annotation to be placed at a specific location on a page.
AnnotationOptions annotation = new AnnotationOptions(
        "This is a major title",                                // Title of the annotation
        "This is the long 'sticky note' comment content...",    // Content of the annotation
        150,                                                    // x-axis coordinate location
        250                                                     // y-axis coordinate location
);
annotation.setIcon(AnnotationIcon.HELP);
annotation.setOpacity(0.9);
annotation.setPrintable(false);
annotation.setHidden(false);
annotation.setOpen(true);
annotation.setReadonly(true);
annotation.setRotateable(true);

// Add the annotation to a specific page of the PDF
AnnotationManager annotationManager = pdf.getAnnotation();
annotationManager.addTextAnnotation(annotation, 0);

// Save the PDF with the modifications
pdf.saveAs(Paths.get("assets/annotated.pdf"));
JAVA

印章和浮水印

IronPDF for Java 擁有強大的 API,提供豐富的 PDF 印章和浮水印功能。通過易於使用的界面,開發人員可以輕鬆地將圖像和 HTML 印章添加到 PDF 中。無論您需要添加公司標誌、保密通知或唯一標識,IronPDF 都能滿足您的需求。API 簡化了向 PDF 添加醒目印章的過程,使其更具專業且個性化的風格。

將文字戳記到 PDF 上

import java.io.IOException;
import java.nio.file.Paths;

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.TextStamper;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
TextStamper stamper1 = new TextStamper();
stamper1.setText("Hello World! Stamp One Here!");
stamper1.setFontFamily("Bungee Spice");
stamper1.setUseGoogleFont(true);

stamper1.setFontSize(100);
stamper1.setBold(true);
stamper1.setItalic(false);
stamper1.setVerticalAlignment(VerticalAlignment.TOP);

PDF.applyStamp(stamper1);
JAVA

在 PDF 上蓋上圖片

import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.stamp.ImageStamper;

PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
ImageStamper imageStamper = new ImageStamper(Paths.get("assets/logo.png"));
// Apply to every page, one page, or some pages
PDF.applyStamp(imageStamper);
PDF.applyStamp(imageStamper, PageSelection.singlePage(2));
PDF.applyStamp(imageStamper, PageSelection.pageRange(0, 2));
JAVA

將條碼加印在 PDF 上

import java.io.IOException;
import java.nio.file.Paths;

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.BarcodeEncoding;
import com.ironsoftware.ironpdf.stamp.BarcodeStamper;
import com.ironsoftware.ironpdf.stamp.HorizontalAlignment;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
BarcodeStamper barcodeStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.Code39);

barcodeStamp.setHorizontalAlignment(HorizontalAlignment.LEFT);
barcodeStamp.setVerticalAlignment(VerticalAlignment.BOTTOM);

PDF.applyStamp(barcodeStamp);
JAVA

將 QR 碼蓋章到 PDF 上

import java.io.IOException;
import java.nio.file.Paths;

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.BarcodeEncoding;
import com.ironsoftware.ironpdf.stamp.BarcodeStamper;
import com.ironsoftware.ironpdf.stamp.HorizontalAlignment;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
BarcodeStamper QRStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.QRCode);
QRStamp.setHeight(50);
QRStamp.setWidth(50);
QRStamp.setHorizontalAlignment(HorizontalAlignment.LEFT);
QRStamp.setVerticalAlignment(VerticalAlignment.BOTTOM);
PDF.applyStamp(QRStamp);
JAVA

在 PDF 上添加浮水印

import java.io.IOException;
import java.nio.file.Paths;

import com.ironsoftware.ironpdf.PdfDocument;

PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
String html = "<h1> Example Title <h1/>";
int watermarkOpacity = 30;
PDF.applyWatermark(html, watermarkOpacity);
JAVA

在PDF中使用表單

IronPDF Java 為開發者提供了一種簡便而高效的方法,用於設置和檢索PDF文檔中表單文本字段的值。通過使用 FormManager 類,開發者只需調用 setFieldValue 方法,並提供所需文本字段的名稱和要填寫的值。

要檢索表單字段的值,開發者可以直接通過 FormManagerFormField 對象集合,使用相關的名稱或索引來訪問該字段。這種對表單字段的控制級別使開發者能夠輕鬆處理動態和交互式的PDF表單。

建立與編輯表單

import com.ironsoftware.ironpdf.PdfDocument;  
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;  
import java.io.IOException;  
import java.nio.file.*;

// #1 Use Case: Create a PDF Form from HTML Form Markup  
Path outputLocation = Paths.get("assets/BasicForm.pdf");  
String formHTML = "<html>"  
  + "<body>"  
  + "<h2>Editable PDF  Form</h2>"  
  + "<form>"  
  + "First name: <br> <input type='text' name='firstname' value=''> <br>"  
  + "Last name: <br> <input type='text' name='lastname' value=''>"  
  + "</form>"  
  + "</body>"  
  + "</html>";  

ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();  
renderOptions.setCreatePdfFormsFromHtml(true);  
PdfDocument.renderHtmlAsPdf(formHTML, renderOptions).saveAs(outputLocation);  

// #2 Use Case: Writing Values to the PDF Form  
PdfDocument form = PdfDocument.fromFile(outputLocation);  

// Set the value of the firstname input field.  
form.getForm().setFieldValue("firstname", "Minnie");  

// Set the value of the lastname input field.  
form.getForm().setFieldValue("lastname", "Mouse");  

// Save the changes to the PDF Form.  
form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
JAVA

填寫現有表單

import com.ironsoftware.ironpdf.PdfDocument;  
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;  
import java.io.IOException;  
import java.nio.file.*;

PdfDocument form = PdfDocument.fromFile("assets/pdfform.pdf");  

// Set the value of the firstname input field.  
form.getForm().setFieldValue("firstname", "Minnie");  

// Set the value of the lastname input field.  
form.getForm().setFieldValue("lastname", "Mouse");  

// Save the changes to the PDF Form.  
form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
JAVA

傳送PDF列印

IronPDF 的列印方法允許開發者輕鬆地 集成 PDF 列印 到他們的應用程式中。只需調用打印方法,操作系統的打印對話框將會打開,讓用戶可以調整打印設置,如打印機、紙張大小和打印份數。

import com.ironsoftware.ironpdf.PdfDocument;
import java.awt.print.PrinterException;

PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Created with IronPDF!</h1>");
try {
    pdf.print();
} catch(PrinterException exception) {
    System.out.println("Failed to print PDF");
    exception.printStackTrace();
}
JAVA