푸터 콘텐츠로 바로가기
JAVA용 IRONPDF 사용

Java PDF 편집기 라이브러리(사용 방법 및 코드 예제)

IronPDF's Java PDF Library is a powerful tool for editing and creating PDF documents within Java applications. It simplifies a wide range of PDF editing functions, such as adding signatures, HTML footers, watermarks, and annotations.

With IronPDF, you can easily create PDF files programmatically, efficiently debug your code, and deploy your projects to many supported platforms or environments.

The main goal for most Java PDF libraries is the dynamic generation of PDF files. IronPDF excels at this task, offering a variety of features to meet your needs.

This article delves into some of IronPDF's most important features, providing code examples and explanations. By the end, you'll have a solid understanding of using IronPDF to edit PDFs in Java—perfect for your PDF editing needs.

Edit Document Structure

Manipulating PDF Documents

IronPDF makes managing PDFs effortless with its capability to add PDFs at specific indexes, copy pages either as a range or individually, and delete pages with ease. All these tasks are handled seamlessly in the background.

Add Pages

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

Copy Pages

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

Delete Pages

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

Attach a Cover Page

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

Know more about attaching Cover page in PDF documents at IronPDF.

Merge and Split PDFs

IronPDF Java simplifies the process of merging multiple PDFs into one or splitting an existing PDF using its user-friendly API.

Join Multiple Existing PDF documents into a Single PDF document

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

Splitting a PDF and Extracting Pages

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

Set the Custom Size of PDF documents

IronPDF enables developers to create PDF documents with non-standard dimensions, beyond the conventional A4 size (8½ by 11 inches or 21.59 by 27.94 cm).

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

Here's more tricks regarding the custom size of the PDFs on IronPDF.

Set PDF Orientation

IronPDF for Java allows modification of page orientation in both new and existing PDFs. By default, new PDFs created with IronPDF are set to portrait orientation, but developers can change it by using a ChromePdfRenderOptions instance when converting content (such as HTML, RTFs, and URLs) into PDFs.

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.page.PageRotation;
import com.ironsoftware.ironpdf.render.*;
import java.io.IOException;
import java.nio.file.Paths;

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

For more information, visit the set PDF orientation tutorial on IronPDF's website.

Set Custom Margins of PDF

IronPDF creates new PDFs with a default margin of 25mm on all sides (top, bottom, left, right). However, developers can customize each margin with specific measurements using 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

Visit the IronPDF website to learn more about setting custom margins for PDF documents.

Convert PDF Documents to Images

IronPDF can export pages of a loaded PDF file, converted source content, or a modified PDF with headers, footers, margins, etc., into images that can be saved to a file system, stored in a database, or transmitted over networks.

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

Add Background and Foreground

IronPDF provides addBackgroundPdf and addForegroundPdf methods for adding a specific background or foreground element to PDFs. These methods enable developers to incorporate content from one PDF as the background or foreground of another PDF, making it efficient for generating collections of PDFs based on a common design template.

Add PDF as Background

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

Add PDF as Foreground

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

Edit Document Properties

Add and Use PDF Metadata

IronPDF offers the ability to modify PDF metadata and security features, including making PDFs read-only, unprintable, password-protected, and encrypted. In IronPDF for Java, the MetadataManager can access and edit a PDF's metadata. The MetadataManager class provides direct access to metadata content and allows developers to read and edit common metadata properties through getters and setters with the same names.

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

Digital Signatures

IronPDF for Java allows secure signing of new or existing PDF files using either X509Certificate2 digital certificates in .pfx or .p12 format. By digitally signing a PDF, its authenticity is guaranteed, preventing alterations without proper certificate validation. This enhances the reliability of the document.

For a free way to generate a signing certificate, Adobe Reader offers instructions in its Digital ID tutorial.

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

Compress PDFs

IronPDF reduces PDF file size with its compressImages method in the PdfDocument class, making it easy to compress PDFs with large images. This optimization leads to significant savings in storage space and cost while transmitting PDFs across email and other communication channels.

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

Editing PDF Content

Add Headers and Footers

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. Template tags like {date}, {time}, and {page} can be used with customized text.

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

Bookmarks

With the BookmarkManager class, developers can create a hierarchical structure of bookmarks within a PDF, allowing users to easily navigate to different sections. To add a new bookmark, use the add method, specifying the title and page number of the bookmark. Bookmarks can be nested to create a more organized structure.

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

Add and Edit Annotations

IronPDF can add "sticky note" style annotations to specific pages of a PDF using the AnnotationManager and AnnotationOptions classes. Create text-based annotations by providing text and (x, y) coordinates to the AnnotationOptions constructor, then use the addTextAnnotation method of the AnnotationManager to add the annotation to the desired page.

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

Stamping and Watermarking

IronPDF for Java has a powerful API offering extensive stamping and watermarking capabilities. With its easy-to-use interface, developers can quickly add images and HTML stamps to their PDFs. Whether you need a company logo, a confidentiality notice, or a unique identifier, IronPDF has you covered, allowing you to add stamps to your PDFs with ease and professionalism.

Stamp Text onto a 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

Stamp an Image onto a 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

Stamp a Barcode onto a 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

Stamp a QR Code onto a 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

Add a Watermark to a 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

Using Forms in PDFs

IronPDF Java provides a straightforward and efficient way to set and retrieve values from form text fields in a PDF document using the FormManager class. Developers can call the setFieldValue method to provide the text field name and value.

Retrieve a form field's value directly through FormManager's collection of FormField objects, using the relevant name or index. This level of control over form fields makes it easy to work with dynamic and interactive PDF forms.

Create and Edit Forms

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

Fill Existing Forms

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

Send PDF for Printing

IronPDF's print method allows developers to easily integrate PDF printing into their applications. By calling the [print](/java/object-reference/api/com/ironsoftware/ironpdf/PdfDocument.html#print()) method, the operating system's print dialog will open, offering users options to adjust settings such as the printer, paper size, and the number of copies.

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

Conclusion

IronPDF is a comprehensive PDF library for Java offering a wide range of features for creating, editing, and manipulating PDF documents. It has robust methods for text and image extraction, allowing developers to access and process PDF content. IronPDF also provides flexibility in customizing PDF metadata and security settings, such as making a PDF read-only or password-protected. It includes a method for compressing PDFs, reducing file size, and improving transmission efficiency.

The library allows the addition of custom headers and footers, as well as annotations, to a PDF document. The bookmarking feature enables developers to add bookmarks for easy navigation within a PDF.

IronPDF offers a free trial key allowing users to test its features and capabilities before making a purchase. The IronPDF Java license starts at $799, offering a cost-effective solution for businesses and individuals looking to secure and manage their PDF files.

자주 묻는 질문

Java PDF 편집기 라이브러리의 주요 기능은 무엇인가요?

Java PDF 편집기 라이브러리는 서명, HTML 바닥글, 워터마크, 주석 추가 등 PDF 편집 및 생성을 위한 포괄적인 도구를 제공합니다. 또한 PDF 병합 및 분할, 크기 및 방향 사용자 지정, PDF를 이미지로 변환하는 기능도 지원합니다.

PDF 라이브러리를 Java 프로젝트에 통합하려면 어떻게 해야 하나요?

IronPDF와 같은 PDF 라이브러리를 Java 프로젝트에 통합하려면 공식 IronPDF 사이트에서 라이브러리를 다운로드하고 프로젝트의 빌드 구성에 종속성으로 추가하세요.

Java에서 PDF 문서의 구조를 수정하려면 어떻게 해야 하나요?

IronPDF를 사용하여 Java에서 PDF 문서의 구조를 수정할 수 있습니다. prependPdf, copyPages, removePages와 같은 메서드를 활용하여 페이지를 추가, 복사 및 삭제할 수 있습니다.

PDF에 사용자 지정 여백과 메타데이터를 설정할 수 있나요?

예, IronPDF를 사용하면 사용자 지정 여백을 설정하고 작성자 및 키워드를 포함한 PDF 메타데이터를 수정할 수 있는 MetadataManager 클래스를 사용할 수 있습니다.

Java를 사용하여 PDF 문서를 이미지 형식으로 변환할 수 있나요?

IronPDF를 사용하면 이미지 크기와 DPI를 정의할 수 있는 toBufferedImages 메서드를 사용하여 PDF 페이지를 이미지 형식으로 변환할 수 있습니다.

PDF 파일에 사용자 지정 워터마크를 추가하려면 어떻게 해야 하나요?

PDF 파일에 사용자 정의 워터마크를 추가하려면 IronPDF의 applyWatermark 메서드를 사용하세요. HTML과 같은 워터마크 콘텐츠를 지정하고 불투명도를 조정할 수 있습니다.

IronPDF는 PDF 문서에 대한 비밀번호 보호를 지원하나요?

예, IronPDF는 비밀번호 보호를 지원하므로 무단 액세스 및 변경을 방지하여 문서를 보호할 수 있습니다.

Java에서 PDF 양식을 처리하는 데 사용할 수 있는 도구에는 어떤 것이 있나요?

IronPDF는 PDF 양식 작성, 편집 및 채우기를 위한 FormManager 클래스를 제공합니다. 이 클래스는 양식 필드에서 값을 설정하고 검색하는 작업을 용이하게 합니다.

PDF의 디지털 서명으로 문서 보안을 보장하려면 어떻게 해야 하나요?

IronPDF는 X509Certificate2 디지털 인증서를 사용하여 PDF 문서에 안전하게 서명하여 진위성을 보장하고 무단 변경을 방지합니다.

PDF 파일을 압축하여 크기를 줄일 수 있나요?

IronPDF에는 PDF 파일을 압축하는 방법이 포함되어 있어 문서 품질을 유지하면서 파일 크기를 줄이는 데 도움이 됩니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.