IRONSOFTWAREHOME
USING IRONPDF FOR JAVA

Java PDF 編輯器庫(如何使用和程式碼範例)

Curtis Chau
Curtis Chau
Updated: 2026年4月21日

IronPDF的Java PDF程式庫是一個強大的工具,用於在Java應用程式中編輯和建立PDF文件。 它簡化了廣泛的PDF編輯功能,例如新增簽名、HTML頁腳、水印和註解。

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

大多數Java PDF程式庫的主要目標是動態生成PDF文件。 IronPDF在這項任務中表現優異,提供各種功能來滿足您的需求。

本文深入探討了IronPDF的一些重要功能,提供程式碼範例和說明。 到最後,您將對在Java中使用IronPDF編輯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();
        }
    }
}
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();
        }
    }
}
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();
        }
    }
}
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);
        }
    }
}
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"));
    }
}
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();
        }
    }
}
Java

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

這裡還有更多關於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"));
    }
}
Java

欲了解更多資訊,請存取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();
        }
    }
}
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();
        }
    }
}
Java

新增背景和前景

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

壓縮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();
        }
    }
}
Java

編輯PDF內容

新增頁眉和頁腳

IronPDF允許您使用ChromePdfRenderOptionsHtmlHeaderFooter新增自定義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);
        }
    }
}
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);
        }
    }
}
Java

書簽

使用BookmarkManager類,開發者可以建立PDF內部的書簽層次結構,允許使用者輕鬆導航到不同的部分。 要新增新書簽,請使用add方法,指定書簽的標題和頁碼。 書簽可以被巢狀以建立更有組織的結構。

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

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可以使用AnnotationManagerAnnotationOptions類將"便箋"風格註釋新增到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();
        }
    }
}
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();
        }
    }
}
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();
        }
    }
}
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();
        }
    }
}
Java

將QR碼加印到PDF上

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

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

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

結論

IronPDF是Java一個綜合的PDF程式庫,提供建立、編輯和操作PDF文件的廣泛功能。 它擁有強大的方法可進行文字和圖像提取,允許開發者存取和處理PDF內容。 IronPDF還提供在定制PDF元資料和安全設置方面的靈活性,例如使PDF只讀或受密碼保護。 它包括一種壓縮PDF的方法,減少文件大小並提高傳輸效率。

此程式庫允許向PDF文件新增自定義的頁眉和頁腳以及註釋。 書簽功能使開發者可以新增書簽,方便導航PDF內部。

IronPDF提供免費試用金鑰,允許使用者在購買前測試其功能和能力。 IronPDF Java許可證從$999開始,為希望保障和管理其PDF文件的企業和個人提供具成本效益的解決方案。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

...
閱讀更多

相關文章

Key in blue circle

立即免費取得 30 天試用金鑰

無任何限制。100% 解鎖。無需信用卡。

bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預訂您的免費 即時演示
Booking Badge

全球數百萬工程師的信任

Iron Software的客戶商標
獲取您的無義務諮詢
填寫以下表格或發送電子郵件至sales@ironsoftware.com
您的詳細資訊始終保持機密。
全球數百萬工程師的信任
Iron Software的客戶商標
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立