Java PDF 編輯器庫(如何使用和程式碼範例)
IronPDF的Java PDF程式庫是一個強大的工具,用於在Java應用程式中編輯和建立PDF文件。 它簡化了廣泛的PDF編輯功能,例如新增簽名、HTML頁腳、水印和註解。
使用IronPDF,您可以輕鬆地以程式化方式建立PDF文件,並高效地除錯您的程式碼,將您的項目部署到許多支持的平台或環境中。
大多數Java PDF程式庫的主要目標是動態生成PDF文件。 IronPDF在這項任務中表現優異,提供各種功能來滿足您的需求。
本文深入探討了IronPDF的一些重要功能,提供程式碼範例和說明。 到最後,您將對在Java中使用IronPDF編輯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);
}
}
}
了解更多關於在IronPDF的PDF文件中附加封面頁面。
合併和拆分PDF
IronPDF Java簡化了將多個PDF合併為一個或使用其使用者友好的API拆分現有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½ × 11英寸或21.59 × 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和現有PDF的頁面方向。 預設情況下,使用IronPDF建立的新PDF設置為縱向,但開發者可以藉由在將內容(例如HTML,RTFs和URLs)轉換為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"));
}
}
欲了解更多資訊,請存取<IronPDFs網站上的PDF方向設置教程
設置PDF的自定義邊距
IronPDF建立的新PDF,所有邊(上、下、左、右)預設邊距為25mm。 然而,開發者可以使用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](/java/object-reference/api/com/ironsoftware/ironpdf/PdfDocument.html#addBackgroundPdf(com.ironsoftware.ironpdf.PdfDocument)和[addForegroundPdf](/java/object-reference/api/com/ironsoftware/ironpdf/PdfDocument.html#addForegroundPdf(com.ironsoftware.ironpdf.PdfDocument)方法,用於將特定背景或前景元素新增到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允許使用X509Certificate2數字證書以.pfx或.p12格式安全地簽署新或現有的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通過[compressImages](/java/object-reference/api/com/ironsoftware/ironpdf/PdfDocument.html#compressImages(int)方法在PdfDocument類中減少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](/java/object-reference/api/com/ironsoftware/ironpdf/annotation/AnnotationManager.html#addTextAnnotation(com.ironsoftware.ironpdf.annotation.AnnotationOptions,int)方法將註釋新增到所需頁面。
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();
}
}
}
將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;
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](/java/object-reference/api/com/ironsoftware/ironpdf/form/FormManager.html#setFieldValue(java.lang.String,java.lang.String)方法,提供文字框名稱和值。
通過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許可證從$999開始,為希望保障和管理其PDF文件的企業和個人提供具成本效益的解決方案。
常見問題
Java PDF 編輯器程式庫的主要功能是什麼?
Java PDF 編輯器程式庫提供全方位的工具用於編輯和建立 PDF,其中包括新增簽名、HTML 頁腳、水印和註釋。它還支援合併和拆分 PDF,自定義大小和方向,以及將 PDF 轉換為圖像。
如何將 PDF 程式庫整合到我的 Java 專案中?
要將像 IronPDF 這樣的 PDF 程式庫整合到您的 Java 專案中,請從官方 IronPDF 網站下載程式庫並將其作為專案的構建配置中的一個依賴項新增。
如何在 Java 中修改 PDF 文件的結構?
您可以使用 IronPDF 在 Java 中修改 PDF 文件的結構。利用 like prependPdf、copyPages 和 removePages 方法來新增、複製和刪除頁面。
是否可以為 PDF 設置自訂邊距和元資料?
是的,IronPDF 允許您設置自訂邊距並修改 PDF 的元資料,包括作者和關鍵字,使用 MetadataManager 類。
我可以使用 Java 將 PDF 文件轉換為圖像格式嗎?
using IronPDF,您可以使用 toBufferedImages 方法將 PDF 頁面轉換為圖像格式,其中可以定義圖像尺寸和 DPI。
如何在 PDF 文件中新增自訂水印?
要在 PDF 文件中新增自訂水印,使用 IronPDF 的 applyWatermark 方法。您可以指定如 HTML 的水印內容,並調整其不透明度。
IronPDF 是否支持 PDF 文件的密碼保護?
是的,IronPDF 支持密碼保護,允許您通過防止未經授權的存取和更改來保護文件。
在 Java 中有哪些工具可用於處理 PDF 表單?
IronPDF 提供一個 FormManager 類用於建立、編輯和填充 PDF 表單。它便於設定和檢索表單欄位中的值。
如何使用 PDF 中的數位簽名來確保文件安全?
IronPDF 使使用 X509Certificate2 數位證書的 PDF 文件安全簽署成為可能,確保真實性並防止未經授權的更改。
是否可以壓縮 PDF 文件以減小其大小?
IronPDF 包括壓縮 PDF 文件的方法,這有助於降低文件大小,同時保持文件質量。





