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

Java PDF 編輯器庫(如何使用和代碼示例)

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

使用 IronPDF,您可以輕鬆地以編程方式創建 PDF 文件,高效地調試代碼,並將項目部署到許多支持的平台或環境中。

大多數 Java PDF 庫的主要目標是動態生成 PDF 文件。 IronPDF 在這項任務中表現出色,提供各種特性來滿足您的需求。

這篇文章深入探討了 IronPDF 的一些最重要特性,並提供代碼示例和解釋。 到最後,您將對如何在 Java 中使用 IronPDF 編輯 PDF 有深刻的理解——完美滿足您的 PDF 編輯需求。

class="hsg-featured-snippet">

如何使用 Java PDF 編輯庫

  1. 安裝用於編輯 PDF 的 Java 庫
  2. 使用 prependPdfcopyPagesremovePages 方法來添加、複製和刪除 PDF
  3. 使用 merge 方法合併 PDF 並使用 copyPages 方法拆分 PDF
  4. 使用自定義紙張尺寸創建新 PDF
  5. 編輯 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();
        }
    }
}
JAVA

複製頁面

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();
        }
    }
}
JAVA

刪除頁面

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();
        }
    }
}
JAVA

附加封面頁

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

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);
        }
    }
}
JAVA

了解更多 在 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"));
    }
}
JAVA

拆分 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();
        }
    }
}
JAVA

設置 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"));
    }
}
JAVA

這裡有更多關於 IronPDF 中 PDF 的自定義尺寸 技巧。

設置 PDF 排版方向

IronPDF for Java 允許修改新建或現有 PDF 文件的頁面方向。 默認情況下,使用 IronPDF 創建的新 PDF 設置為縱向方向,但開發人員可以通過使用 ChromePdfRenderOptions 實例將內容(如 HTML、RTF 和 URL)轉換為 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"));
    }
}
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"));
    }
}
JAVA

欲了解更多信息,請訪問 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();
        }
    }
}
JAVA

訪問 IronPDF 網站了解更多關於 設置 PDF 文檔的自定義邊距

將 PDF 文檔轉換為圖像

IronPDF 可以將加載的 PDF 文件的頁面、轉換的源內容或修改的 PDF(具有頁眉、頁腳、邊距等)導出為圖像,這些圖像可以保存到文件系統、存儲在數據庫中或通過網絡傳輸。

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

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();
        }
    }
}
JAVA

添加背景和前景

IronPDF provides addBackgroundPdf and addForegroundPdf methods for adding a specific background or foreground element to PDFs. 這些方法使開發人員能夠將一個 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();
        }
    }
}
JAVA

將 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();
        }
    }
}
JAVA

編輯文檔屬性

添加和使用 PDF 元數據

IronPDF 提供 修改 PDF 元數據 和安全功能的能力,包括使 PDF 只能讀取、無法打印、密碼保護和加密。 在 IronPDF for Java 中,MetadataManager 可以訪問和編輯 PDF 的元數據。 MetadataManager 類提供對元數據內容的直接訪問,允許開發人員通過相同名稱的 getter 和 setter 讀取和編輯常見的元數據屬性。

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

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();
        }
    }
}
JAVA

數字簽名

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();
        }
    }
}
JAVA

壓縮 PDF

IronPDF reduces PDF file size with its compressImages method in the PdfDocument class, making it easy to compress PDFs with large images. 此優化在儲存空間和通過 email 及其他通信渠道發送 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();
        }
    }
}
JAVA

編輯 PDF 內容

添加頁眉和頁腳

IronPDF allows you to add custom HTML headers and footers using the ChromePdfRenderOptions and HtmlHeaderFooter classes. It also supports custom text headers and footers through the TextHeaderFooter class, which allows specifying text for the header/footer's left, right, or center regions. 可以用自定義文本使用模板標籤如{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);
        }
    }
}
JAVA

文本頁眉和頁腳

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

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);
        }
    }
}
JAVA

書籤

With the BookmarkManager class, developers can create a hierarchical structure of bookmarks within a PDF, allowing users to easily navigate to different sections. 要添加新書籤,使用添加方法,指定書籤的標題和頁碼。 書籤可以嵌套以創建更有組織的結構。

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();
        }
    }
}
JAVA

添加和編輯註釋

IronPDF can add "sticky note" style annotations to specific pages of a PDF using the AnnotationManager and AnnotationOptions classes. 通過提供文本和 (x, y) 坐標給 AnnotationOptions 構造函數創建基於文本的註釋,然後使用 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();
        }
    }
}
JAVA

蓋章和水印

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();
        }
    }
}
JAVA

在 PDF 上蓋章圖像

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

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();
        }
    }
}
JAVA

在 PDF 上蓋章條形碼

import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.BarcodeEncoding;
import com.ironsoftware.ironpdf.stamp.BarcodeStamper;
import com.ironsoftware.ironpdf.stamp.HorizontalAlignment;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;

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();
        }
    }
}
JAVA

在 PDF 上蓋章二維碼

import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.BarcodeEncoding;
import com.ironsoftware.ironpdf.stamp.BarcodeStamper;
import com.ironsoftware.ironpdf.stamp.HorizontalAlignment;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;

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();
        }
    }
}
JAVA

在 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();
        }
    }
}
JAVA

在 PDF 中使用表單

IronPDF Java 提供了一種簡單高效的方法來使用 FormManager 類設置和檢索 PDF 文檔中表單文本字段的值。 開發人員可以調用 setFieldValue 方法來提供文本字段的名稱和值。

可以直接通過 FormManagerFormField 對象集合使用相關名稱或索引檢索表單字段的值。 這種對表單字段的控制水平使得處理動態和互動式 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();
        }
    }
}
JAVA

填充現有表單

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();
        }
    }
}
JAVA

發送 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();
        }
    }
}
JAVA

結論

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 文檔的結構。使用諸如 prependPdfcopyPagesremovePages 方法來添加、複製和刪除頁面。

是否可以為 PDF 設置自定義邊距和元數據?

是的,IronPDF 允許您設置自定義邊距和修改 PDF 元數據,包括作者和關鍵詞,使用 MetadataManager 類。

我可以使用 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 文件的方法,這有助於減少文件大小,同時保持文件質量。

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

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

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

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