使用 IRONPDF FOR JAVA

Java PDF 編輯器庫(使用方法及代碼範例)

已更新 2024年9月1日
分享:

IronPDF 是一個強大的Java PDF庫,用於在Java中編輯和創建PDF文檔。它簡化了多種PDF編輯功能,如添加簽名、HTML頁腳、水印和註釋。

利用IronPDF,您可以輕鬆地以程式方式創建PDF文件,輕鬆調試代碼,並將項目部署到任何支持的平台或環境。

大多數Java PDF庫的主要目標是動態生成PDF文件。使用IronPDF,您可以完成這項任務。

本文將探討IronPDF的一些最重要功能,並為您提供代碼示例和解釋。通過本文的學習,您將深入了解如何使用IronPDF在Java中編輯PDF。這是您PDF編輯需求的完美工具。

編輯文件結構

操作 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 com.ironsoftware.ironpdf.headerfooter.TextHeaderFooter;

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;

// 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 提供 addBackgroundPdfaddForegroundPdf 方法對於 將特定的背景或前景元素添加到 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;

PdfDocument foregroundPdf = PdfDocument.fromFile(Paths.get("assets/MyForeground.pdf"));  
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://www.nuget.org/packages/IronPdf");  
pdf.addForegroundPdf(foregroundPdf);  

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

編輯文件屬性

添加和使用 PDF 元數據

IronPDF 提供了 修改 PDF 中的元數據 以及安全功能,包括使PDF文件只讀、不可打印、受密碼保護和加密。在IronPDF for Java中, MetadataManager 可以用來存取和編輯 PDF 的元資料。MetadataManager 類提供對元資料內容的直接存取,並允許開發者通過具有相同名稱的 getter 和 setter 輕鬆讀取和編輯常用的元資料屬性。

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

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 教程.

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 使用其技術減少 PDF 文件大小 壓縮圖片 方法在 PdfDocument class,輕鬆壓縮包含大圖片的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 頁首和頁尾 使用 ChromePdfRenderOptions 轉換為 PDF HtmlHeaderFooter 類別。IronPDF 使 自訂文字標頭和頁尾 通過 IronPDF 添加到 PDF 中 文字頁眉頁腳 類別,允許指定頁眉/頁腳左側、右側或中間區域的文本。這包括使用內建的模板標籤如 {日期}, {時間},和 {頁面},或任何其他所需的自訂文本。

HTML 標頭和頁尾

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.headerfooter.HtmlHeaderFooter;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

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;
import java.nio.file.Paths;

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

書籤

通過 書籤管理器, 開發者可以創建一個層次結構的 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可以添加 「便利貼」風格的註解到特定頁面 使用 PDF 的 AnnotationManagerAnnotationOptions 類別。開發人員可以通過提供文本來創建基於文本的註釋。 (x,y) 將座標作為參數傳遞給 AnnotationOptions 構造函數,然後使用 addTextAnnotation 使用 AnnotationManager 的方法將註解添加到所需的頁面。

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 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 列印 至於他們的應用程序。只需調用 [列印](/java/object-reference/api/com/ironsoftware/ironpdf/PdfDocument.html#print()) 方法中,操作系統的打印對話框將會打開,為使用者提供調整打印設置的選項,如打印機、紙張尺寸和打印份數。

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

結論

IronPDF 是一個全面的 Java PDF 庫,提供了廣泛的功能來創建、編輯和操作 PDF 文件。它具有強大的文字和圖片提取方法,允許開發者訪問和處理 PDF 中的內容。IronPDF 也提供了自定義 PDF 元數據和安全設置的靈活性,例如將 PDF 設為唯讀或加密保護。此外,它還提供壓縮 PDF 的方法,減少文件大小,提高傳輸效率。

該庫包括添加自定義頁眉和頁腳以及注釋到 PDF 文件的能力。書籤功能使開發者能夠添加書籤,以便於在 PDF 內的導航。

IronPDF 提供了一個 免費試用密鑰 讓用戶在購買前測試其功能和效能。 IronPDF Java 授權 起價為 $749,為尋求保障和管理 PDF 檔案的企業和個人提供了一種經濟實惠的解決方案。

< 上一頁
如何使用 Java 合併兩個 PDF 文件
下一個 >
Java PDF 生成器(範例程式教學)

準備開始了嗎? 版本: 2024.9 剛剛發布

免費 Maven 下載 查看許可證 >