Java PDF 編輯器庫(使用方法及程式碼範例)
IronPDF 的 Java PDF 文件庫是一個強大的工具,用於在 Java 應用程式中編輯和建立 PDF 文件。 它簡化了各種 PDF 編輯功能,例如添加簽名、HTML 頁腳、浮水印和註釋。
透過 IronPDF,您可以輕鬆地以程式設計方式建立 PDF 文件,有效地偵錯程式碼,並將專案部署到許多受支援的平台或環境中。
大多數 Java PDF 程式庫的主要目標是動態產生 PDF 檔案。 IronPDF 在這方面表現出色,提供各種功能來滿足您的需求。
本文深入探討了 IronPDF 的一些最重要的功能,並提供了程式碼範例和解釋。 到最後,您將對如何使用 IronPDF 在 Java 中編輯 PDF 有紮實的了解——完美滿足您的 PDF 編輯需求。
如何使用 Java PDF 編輯器庫
- 安裝 Java 庫以編輯 PDF 文件
- 使用
prependPdf、copyPages和removePages方法新增、複製和刪除 PDF 文件 - 使用
merge方法合併 PDF,並使用copyPages方法分割 PDF。 - 創建具有自定義紙張大小的新 PDF
- 編輯 PDF 元數據
編輯文檔結構
操作PDF文檔
IronPDF 能夠輕鬆管理 PDF 文件,它可以按特定索引添加 PDF 文件,複製頁面(無論是批量複製還是單獨複製),以及輕鬆刪除頁面。 所有這些任務都在後台無縫處理。
新增頁面
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
public class AddPagesExample {
public static void main(String[] args) {
try {
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"));
} catch (IOException e) {
e.printStackTrace();
}
}
}import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
public class AddPagesExample {
public static void main(String[] args) {
try {
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"));
} catch (IOException e) {
e.printStackTrace();
}
}
}影印頁
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
public class CopyPagesExample {
public static void main(String[] args) {
try {
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PDF.copyPages(0, 1).saveAs("report_highlight.pdf");
} catch (IOException e) {
e.printStackTrace();
}
}
}import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
public class CopyPagesExample {
public static void main(String[] args) {
try {
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PDF.copyPages(0, 1).saveAs("report_highlight.pdf");
} catch (IOException e) {
e.printStackTrace();
}
}
}刪除頁面
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
public class DeletePagesExample {
public static void main(String[] args) {
try {
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PDF.removePages(PageSelection.lastPage()).saveAs(Paths.get("assets/lastPageRemove.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
public class DeletePagesExample {
public static void main(String[] args) {
try {
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PDF.removePages(PageSelection.lastPage()).saveAs(Paths.get("assets/lastPageRemove.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}附上封面頁
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;
public class AttachCoverPageExample {
public static void main(String[] args) {
// Create a Sample Cover Page using RenderHtmlAsPdf
PdfDocument coverPage = PdfDocument.renderHtmlAsPdf("<h1>This is a Cover Page</h1>");
PdfDocument webpage = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
// 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);
}
}
}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;
public class AttachCoverPageExample {
public static void main(String[] args) {
// Create a Sample Cover Page using RenderHtmlAsPdf
PdfDocument coverPage = PdfDocument.renderHtmlAsPdf("<h1>This is a Cover Page</h1>");
PdfDocument webpage = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
// 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);
}
}
}合併和拆分PDF
IronPDF Java 透過其用戶友好的 API,簡化了將多個 PDF 合併為一個 PDF 或拆分現有 PDF 的過程。
將多個現有 PDF 文檔合併為一個 PDF 文檔
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class MergePdfsExample {
public static void main(String[] args) {
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"));
}
}import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class MergePdfsExample {
public static void main(String[] args) {
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"));
}
}分割PDF文件並提取頁面
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class SplitPdfExample {
public static void main(String[] args) {
try {
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PdfDocument copied = PDF.copyPage(0);
copied.saveAs("assets/Split.pdf");
} catch (IOException e) {
e.printStackTrace();
}
}
}import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class SplitPdfExample {
public static void main(String[] args) {
try {
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
PdfDocument copied = PDF.copyPage(0);
copied.saveAs("assets/Split.pdf");
} catch (IOException e) {
e.printStackTrace();
}
}
}設定 PDF 文件的自訂大小
IronPDF 使開發人員能夠創建非標準尺寸的 PDF 文檔,超越傳統的 A4 尺寸(8½ x 11 英寸或 21.59 x 27.94 厘米)。
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import com.ironsoftware.ironpdf.render.PaperSize;
import java.io.IOException;
import java.nio.file.Paths;
public class CustomSizeExample {
public static void main(String[] args) {
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"));
}
}import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import com.ironsoftware.ironpdf.render.PaperSize;
import java.io.IOException;
import java.nio.file.Paths;
public class CustomSizeExample {
public static void main(String[] args) {
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"));
}
}以下是關於IronPDF中自訂PDF大小的更多技巧。
設定PDF方向
IronPDF for Java 允許修改新建和現有 PDF 中的頁面方向。 預設情況下,使用 IronPDF 建立的新 PDF 設定為縱向方向,但開發人員可以在將內容(例如 HTML、RTF 和 URL)轉換為 PDF 時,請使用ChromePdfRenderOptions實例來變更此設定。
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;
public class SetOrientationExample {
public static void main(String[] args) {
// Load an existing PDF
PdfDocument existingPdf = PdfDocument.fromFile("assets/sample.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"));
}
}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;
public class SetOrientationExample {
public static void main(String[] args) {
// Load an existing PDF
PdfDocument existingPdf = PdfDocument.fromFile("assets/sample.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"));
}
}有關更多信息,請訪問IronPDF 網站上的設定 PDF 方向教程。
設定PDF的自訂邊距
IronPDF 建立的新 PDF 檔案預設邊距為 25 毫米(上、下、左、右)。 但是,開發人員可以使用 IronPDF 為每個邊距自訂特定尺寸。
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.Paths;
public class CustomMarginsExample {
public static void main(String[] args) {
// Set Margins (in millimeters)
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setMarginTop(40);
renderOptions.setMarginLeft(20);
renderOptions.setMarginRight(20);
renderOptions.setMarginBottom(40);
try {
PdfDocument.renderHtmlFileAsPdf("assets/wikipedia.html", renderOptions).saveAs(Paths.get("assets/MyContent.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.Paths;
public class CustomMarginsExample {
public static void main(String[] args) {
// Set Margins (in millimeters)
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
renderOptions.setMarginTop(40);
renderOptions.setMarginLeft(20);
renderOptions.setMarginRight(20);
renderOptions.setMarginBottom(40);
try {
PdfDocument.renderHtmlFileAsPdf("assets/wikipedia.html", renderOptions).saveAs(Paths.get("assets/MyContent.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}請造訪 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;
public class ConvertPdfToImagesExample {
public static void main(String[] args) {
try {
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));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}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;
public class ConvertPdfToImagesExample {
public static void main(String[] args) {
try {
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));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}增加背景和前景
IronPDF 提供addBackgroundPdf 和addForegroundPdf 方法,用於為 PDF 添加特定的背景或前景元素。 這些方法使開發人員能夠將一個 PDF 中的內容作為另一個 PDF 的背景或前景,從而能夠有效地基於通用設計模板生成 PDF 集合。
新增 PDF 作為背景
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class AddBackgroundExample {
public static void main(String[] args) {
try {
// 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://ironpdf.com");
// Add the background PDFs to the newly-rendered document.
pdf.addBackgroundPdf(backgroundPdf);
pdf.saveAs(Paths.get("assets/BackgroundPdf.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class AddBackgroundExample {
public static void main(String[] args) {
try {
// 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://ironpdf.com");
// Add the background PDFs to the newly-rendered document.
pdf.addBackgroundPdf(backgroundPdf);
pdf.saveAs(Paths.get("assets/BackgroundPdf.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}將 PDF 新增為前景
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class AddForegroundExample {
public static void main(String[] args) {
try {
PdfDocument foregroundPdf = PdfDocument.fromFile(Paths.get("assets/MyForeground.pdf"));
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
pdf.addForegroundPdf(foregroundPdf);
pdf.saveAs(Paths.get("assets/BackgroundForegroundPdf.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class AddForegroundExample {
public static void main(String[] args) {
try {
PdfDocument foregroundPdf = PdfDocument.fromFile(Paths.get("assets/MyForeground.pdf"));
PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
pdf.addForegroundPdf(foregroundPdf);
pdf.saveAs(Paths.get("assets/BackgroundForegroundPdf.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}編輯文檔屬性
新增和使用 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;
public class EditMetadataExample {
public static void main(String[] args) {
try {
// 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"));
} catch (IOException e) {
e.printStackTrace();
}
}
}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;
public class EditMetadataExample {
public static void main(String[] args) {
try {
// 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"));
} catch (IOException e) {
e.printStackTrace();
}
}
}數位簽名
IronPDF for Java 允許使用 .pfx 或 .p12 格式的X509Certificate2數位憑證對新的或現有的 PDF 檔案進行安全簽署。 透過對 PDF 文件進行數位簽名,可以確保其真實性,防止未經適當證書驗證的篡改。 這提高了文件的可靠性。
Adobe Reader在其數位 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;
public class DigitalSignatureExample {
public static void main(String[] args) {
try {
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Load the X509Certificate2 digitals certificates from .pfx or .p12 formats
File path = new File("assets/Ironpdf.pfx");
byte[] certificate = new byte[(int) path.length()];
// Sign PDF with a specific signature
Signature signature = new Signature(certificate, "1234");
SignatureManager manager = PDF.getSignature();
manager.signPdfWithSignature(signature);
PDF.saveAs(Paths.get("assets/signed_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}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;
public class DigitalSignatureExample {
public static void main(String[] args) {
try {
PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
// Load the X509Certificate2 digitals certificates from .pfx or .p12 formats
File path = new File("assets/Ironpdf.pfx");
byte[] certificate = new byte[(int) path.length()];
// Sign PDF with a specific signature
Signature signature = new Signature(certificate, "1234");
SignatureManager manager = PDF.getSignature();
manager.signPdfWithSignature(signature);
PDF.saveAs(Paths.get("assets/signed_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}壓縮PDF文件
IronPDF 透過PdfDocument類別中的[compressImages](/java/object-reference/api/com/ironsoftware/ironpdf/PdfDocument.html#compressImages(int)方法來減少 PDF 檔案大小,從而可以輕鬆壓縮包含大圖像的 PDF。 這種優化可以顯著節省儲存空間和成本,同時也能透過電子郵件和其他通訊管道傳輸 PDF 文件。
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class CompressPdfExample {
public static void main(String[] args) {
try {
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"));
} catch (IOException e) {
e.printStackTrace();
}
}
}import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class CompressPdfExample {
public static void main(String[] args) {
try {
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"));
} catch (IOException e) {
e.printStackTrace();
}
}
}編輯PDF內容
新增頁首和頁尾
IronPDF 可讓您使用ChromePdfRenderOptions和HtmlHeaderFooter類別新增自訂 HTML 頁首和頁尾。 它還支援透過TextHeaderFooter類別自訂文字頁首和頁腳,允許為頁首/頁尾的左側、右側或中心區域指定文字。 可以使用{date}、{time} 和 {page}等範本標籤以及自訂文字。
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;
public class HtmlHeaderFooterExample {
public static void main(String[] args) {
try {
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);
pdf.saveAs(Paths.get("assets/html_headers_footers.pdf"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}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;
public class HtmlHeaderFooterExample {
public static void main(String[] args) {
try {
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);
pdf.saveAs(Paths.get("assets/html_headers_footers.pdf"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}文字頁首和頁尾
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;
public class TextHeaderFooterExample {
public static void main(String[] args) {
try {
// 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);
pdf.saveAs(Paths.get("assets/text_headers_footers.pdf"));
} catch (IOException e) {
System.out.println("Failed to save PDF");
throw new RuntimeException(e);
}
}
}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;
public class TextHeaderFooterExample {
public static void main(String[] args) {
try {
// 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);
pdf.saveAs(Paths.get("assets/text_headers_footers.pdf"));
} catch (IOException e) {
System.out.println("Failed to save PDF");
throw new RuntimeException(e);
}
}
}書籤
透過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;
public class BookmarksExample {
public static void main(String[] args) {
try {
// 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"));
} catch (IOException e) {
e.printStackTrace();
}
}
}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;
public class BookmarksExample {
public static void main(String[] args) {
try {
// 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"));
} catch (IOException e) {
e.printStackTrace();
}
}
}新增和編輯註釋
IronPDF 可以使用AnnotationManager和AnnotationOptions類別在 PDF 的特定頁面中新增"便條"樣式的註解。 透過提供AnnotationOptions建構函式和 (x, y) 座標來建立基於文字的註釋,然後使用AnnotationManager的addTextAnnotation 方法將註解新增至所需的頁面。
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;
public class AnnotationExample {
public static void main(String[] args) {
try {
// 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"));
} catch (IOException e) {
e.printStackTrace();
}
}
}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;
public class AnnotationExample {
public static void main(String[] args) {
try {
// 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"));
} catch (IOException e) {
e.printStackTrace();
}
}
}印章和浮水印
IronPDF for Java 擁有強大的 API,提供廣泛的加蓋和浮水印功能。 憑藉其易於使用的介面,開發人員可以快速地向 PDF 文件中添加圖像和 HTML 圖章。 無論您需要公司商標、保密聲明或唯一識別符,IronPDF 都能滿足您的需求,讓您輕鬆專業地向 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;
public class StampTextExample {
public static void main(String[] args) {
try {
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);
pdf.saveAs(Paths.get("assets/stamped_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}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;
public class StampTextExample {
public static void main(String[] args) {
try {
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);
pdf.saveAs(Paths.get("assets/stamped_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}在 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;
public class StampImageExample {
public static void main(String[] args) {
try {
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));
pdf.saveAs(Paths.get("assets/image_stamped_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}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;
public class StampImageExample {
public static void main(String[] args) {
try {
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));
pdf.saveAs(Paths.get("assets/image_stamped_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}在 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;
public class StampBarcodeExample {
public static void main(String[] args) {
try {
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);
pdf.saveAs(Paths.get("assets/barcode_stamped_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}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;
public class StampBarcodeExample {
public static void main(String[] args) {
try {
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);
pdf.saveAs(Paths.get("assets/barcode_stamped_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}在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;
public class StampQrCodeExample {
public static void main(String[] args) {
try {
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);
pdf.saveAs(Paths.get("assets/qrcode_stamped_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}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;
public class StampQrCodeExample {
public static void main(String[] args) {
try {
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);
pdf.saveAs(Paths.get("assets/qrcode_stamped_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}給PDF加浮水印
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
public class AddWatermarkExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
String html = "<h1> Example Title <h1/>";
int watermarkOpacity = 30;
pdf.applyWatermark(html, watermarkOpacity);
pdf.saveAs(Paths.get("assets/watermarked_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
public class AddWatermarkExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
String html = "<h1> Example Title <h1/>";
int watermarkOpacity = 30;
pdf.applyWatermark(html, watermarkOpacity);
pdf.saveAs(Paths.get("assets/watermarked_sample.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
}在PDF中使用表單
IronPDF Java 提供了一種簡單且有效率的方法,可以使用FormManager類別來設定和檢索 PDF 文件中表單文字欄位的值。 開發者可以呼叫setFieldValue 方法來提供文字欄位名稱和值。
透過FormManager的FormField物件集合,使用相關的名稱或索引直接檢索表單欄位的值。 對表單欄位的這種控制層級使得處理動態和互動式 PDF 表單變得容易。
建立和編輯表單
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.Paths;
public class CreateAndEditFormsExample {
public static void main(String[] args) {
try {
// #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"));
} catch (IOException e) {
e.printStackTrace();
}
}
}import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.Paths;
public class CreateAndEditFormsExample {
public static void main(String[] args) {
try {
// #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"));
} catch (IOException e) {
e.printStackTrace();
}
}
}填寫現有表格
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class FillExistingFormsExample {
public static void main(String[] args) {
try {
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"));
} catch (IOException e) {
e.printStackTrace();
}
}
}import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;
public class FillExistingFormsExample {
public static void main(String[] args) {
try {
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"));
} catch (IOException e) {
e.printStackTrace();
}
}
}發送PDF文件以供列印
IronPDF 的列印方法使開發人員能夠輕鬆地將 PDF 列印整合到他們的應用程式中。 透過呼叫[print](/java/object-reference/api/com/ironsoftware/ironpdf/PdfDocument.html#print() ) 方法,作業系統將開啟列印對話框,為使用者提供調整印表機、紙張尺寸和份數等設定的選項。
import com.ironsoftware.ironpdf.PdfDocument;
import java.awt.print.PrinterException;
public class PrintPdfExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Created with IronPDF!</h1>");
pdf.print();
} catch (PrinterException exception) {
System.out.println("Failed to print PDF");
exception.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}import com.ironsoftware.ironpdf.PdfDocument;
import java.awt.print.PrinterException;
public class PrintPdfExample {
public static void main(String[] args) {
try {
PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Created with IronPDF!</h1>");
pdf.print();
} catch (PrinterException exception) {
System.out.println("Failed to print PDF");
exception.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}結論
IronPDF 是一個功能全面的 Java PDF 函式庫,提供建立、編輯和操作 PDF 文件的各種功能。 它具有強大的文字和圖像提取方法,使開發人員能夠存取和處理 PDF 內容。 IronPDF 也提供了自訂 PDF 元資料和安全設定的靈活性,例如將 PDF 設定為唯讀或密碼保護。 它包含一種壓縮 PDF、減小檔案大小和提高傳輸效率的方法。
該庫允許在 PDF 文件中添加自訂頁首、頁尾以及註釋。 書籤功能使開發人員能夠添加書籤,以便在 PDF 中輕鬆導航。
IronPDF 提供免費試用金鑰,用戶可以在購買前測試其功能和效能。 IronPDF Java 授權起價為$799 ,為希望保護和管理其 PDF 文件的企業和個人提供了一種經濟高效的解決方案。
常見問題解答
Java PDF 編輯器庫的主要特點是什麼?
Java PDF 編輯器庫提供了一系列全面的 PDF 編輯和建立工具,包括新增簽章、HTML 頁尾、浮水印和註解。它還支援合併和拆分 PDF、自訂尺寸和方向,以及將 PDF 轉換為圖像。
如何將PDF庫整合到我的Java專案中?
若要將 IronPDF 等 PDF 庫整合到您的 Java 專案中,請從 IronPDF 官方網站下載程式庫,並將其作為依賴項新增至您專案的建置配置中。
如何在Java中修改PDF文件的結構?
您可以使用 IronPDF 在 Java 中修改 PDF 文件的結構。利用prependPdf 、 copyPages和removePages等方法來新增、複製和刪除頁面。
是否可以為 PDF 設定自訂邊距和元資料?
是的,IronPDF 允許您使用MetadataManager類別設定自訂邊距並修改 PDF 元數據,包括作者和關鍵字。
我可以使用Java將PDF文件轉換為影像格式嗎?
使用 IronPDF,您可以使用toBufferedImages方法將 PDF 頁面轉換為影像格式,您可以在其中定義影像尺寸和 DPI。
如何在PDF文件中新增自訂浮水印?
若要為 PDF 檔案新增自訂浮水印,請使用 IronPDF 的applyWatermark方法。您可以指定浮水印內容(例如 HTML),並調整其不透明度。
IronPDF是否支援PDF文件的密碼保護?
是的,IronPDF 支援密碼保護,可防止未經授權的存取和更改,從而保護文件安全。
Java 中有哪些工具可用於處理 PDF 表單?
IronPDF 提供了一個FormManager類,用於建立、編輯和填寫 PDF 表單。它方便使用者設定和檢索表單欄位的值。
如何確保PDF檔案中數位簽章的安全性?
IronPDF 能夠使用 X509Certificate2 數位憑證對 PDF 文件進行安全簽名,確保真實性並防止未經授權的更改。
是否可以壓縮PDF檔案以減少其大小?
IronPDF 包含壓縮 PDF 文件的方法,有助於在保持文件品質的同時減少文件大小。






