跳至页脚内容
在 JAVA 中使用 IRONPDF

Java PDF 编辑器库 (如何 & 代码示例)

IronPDF 的 Java PDF 库 是一个强大的工具,用于在 Java 应用程序中编辑和创建 PDF 文档。 它简化了各种 PDF 编辑功能,如添加签名、HTML 页脚、水印和注释。

使用 IronPDF,您可以轻松地以编程方式创建 PDF 文件,高效调试代码,并将项目部署到许多支持的平台或环境。

大多数 Java PDF 库的主要目标是动态生成 PDF 文件。 IronPDF 在这方面表现出色,提供了各种功能来满足您的需求。

本文深入探讨了 IronPDF 的一些重要功能,提供了代码示例和解释。 最后,您将对如何使用 IronPDF 在 Java 中编辑 PDF 有一个扎实的理解,非常适合您的 PDF 编辑需求。

class="hsg-featured-snippet">

如何使用 Java PDF 编辑器库

  1. 安装 Java 库以编辑 PDF
  2. 使用prependPdfcopyPagesremovePages方法添加、复制和删除 PDF
  3. 使用merge方法合并 PDF,使用copyPages方法拆分 PDF
  4. 以定制纸张尺寸创建新的 PDF
  5. 编辑 PDF 元数据

编辑文档结构

操作 PDF 文档

IronPDF 使管理 PDF 变得轻而易举,其功能包括在特定索引处添加 PDF,将页面范围或单独复制,并轻松删除页面。 所有这些任务都在后台无缝处理。

添加页面

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

public class AddPagesExample {
    public static void main(String[] args) {
        try {
            PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            PdfDocument coverPagePdf = PdfDocument.renderHtmlAsPdf("<h1>Cover Page</h1><hr>");
            PDF.prependPdf(coverPagePdf);
            PDF.saveAs(Paths.get("report_with_cover.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;

public class AddPagesExample {
    public static void main(String[] args) {
        try {
            PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            PdfDocument coverPagePdf = PdfDocument.renderHtmlAsPdf("<h1>Cover Page</h1><hr>");
            PDF.prependPdf(coverPagePdf);
            PDF.saveAs(Paths.get("report_with_cover.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

复制页面

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

public class CopyPagesExample {
    public static void main(String[] args) {
        try {
            PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            PDF.copyPages(0, 1).saveAs("report_highlight.pdf");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;

public class CopyPagesExample {
    public static void main(String[] args) {
        try {
            PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            PDF.copyPages(0, 1).saveAs("report_highlight.pdf");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

删除页面

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

public class DeletePagesExample {
    public static void main(String[] args) {
        try {
            PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            PDF.removePages(PageSelection.lastPage()).saveAs(Paths.get("assets/lastPageRemove.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;

public class DeletePagesExample {
    public static void main(String[] args) {
        try {
            PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            PDF.removePages(PageSelection.lastPage()).saveAs(Paths.get("assets/lastPageRemove.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

附加封面页

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

public class AttachCoverPageExample {
    public static void main(String[] args) {
        // Create a Sample Cover Page using RenderHtmlAsPdf
        PdfDocument coverPage = PdfDocument.renderHtmlAsPdf("<h1>This is a Cover Page</h1>");
        PdfDocument webpage = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

        // Set the page number of the PDF document to be created to 2.
        HeaderFooterOptions headerFooterOptions = new HeaderFooterOptions();
        headerFooterOptions.setFirstPageNumber(1);
        TextHeaderFooter footer = new TextHeaderFooter();
        footer.setLeftText("");
        footer.setCenterText("Page {page}");
        footer.setRightText("");

        webpage.addTextFooter(footer, headerFooterOptions);

        // Convert a web page's content to a PDF document.
        // Merge the cover page with the web page and save the new PDF to the filesystem.
        try {
            PdfDocument.merge(coverPage, webpage).saveAs(Paths.get("assets/cover_page_pdf.pdf"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.headerfooter.HeaderFooterOptions;
import com.ironsoftware.ironpdf.headerfooter.TextHeaderFooter;
import java.io.IOException;
import java.nio.file.Paths;

public class AttachCoverPageExample {
    public static void main(String[] args) {
        // Create a Sample Cover Page using RenderHtmlAsPdf
        PdfDocument coverPage = PdfDocument.renderHtmlAsPdf("<h1>This is a Cover Page</h1>");
        PdfDocument webpage = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

        // Set the page number of the PDF document to be created to 2.
        HeaderFooterOptions headerFooterOptions = new HeaderFooterOptions();
        headerFooterOptions.setFirstPageNumber(1);
        TextHeaderFooter footer = new TextHeaderFooter();
        footer.setLeftText("");
        footer.setCenterText("Page {page}");
        footer.setRightText("");

        webpage.addTextFooter(footer, headerFooterOptions);

        // Convert a web page's content to a PDF document.
        // Merge the cover page with the web page and save the new PDF to the filesystem.
        try {
            PdfDocument.merge(coverPage, webpage).saveAs(Paths.get("assets/cover_page_pdf.pdf"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
JAVA

了解更多关于 在 IronPDF 中将封面页附加到 PDF 文档 的信息。

合并和拆分 PDF

IronPDF Java 通过其用户友好的 API 简化了将多个 PDF 合并为一个或拆分现有 PDF 的过程。

将多个现有 PDF 文档合并为一个 PDF 文件

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

public class MergePdfsExample {
    public static void main(String[] args) {
        String htmlA = "<p> [PDF_A] </p>" +
                "<p> [PDF_A] 1st Page </p>" +
                "<div style='page-break-after: always;'></div>" +
                "<p> [PDF_A] 2nd Page</p>";
        String htmlB = "<p> [PDF_B] </p>" +
                "<p> [PDF_B] 1st Page </p>" +
                "<div style='page-break-after: always;'></div>" +
                "<p> [PDF_B] 2nd Page</p>";

        PdfDocument pdfA = PdfDocument.renderHtmlAsPdf(htmlA);
        PdfDocument pdfB = PdfDocument.renderHtmlAsPdf(htmlB);
        PdfDocument merged = PdfDocument.merge(pdfA, pdfB);

        merged.saveAs(Paths.get("assets/merged.pdf"));
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;

public class MergePdfsExample {
    public static void main(String[] args) {
        String htmlA = "<p> [PDF_A] </p>" +
                "<p> [PDF_A] 1st Page </p>" +
                "<div style='page-break-after: always;'></div>" +
                "<p> [PDF_A] 2nd Page</p>";
        String htmlB = "<p> [PDF_B] </p>" +
                "<p> [PDF_B] 1st Page </p>" +
                "<div style='page-break-after: always;'></div>" +
                "<p> [PDF_B] 2nd Page</p>";

        PdfDocument pdfA = PdfDocument.renderHtmlAsPdf(htmlA);
        PdfDocument pdfB = PdfDocument.renderHtmlAsPdf(htmlB);
        PdfDocument merged = PdfDocument.merge(pdfA, pdfB);

        merged.saveAs(Paths.get("assets/merged.pdf"));
    }
}
JAVA

拆分 PDF 并提取页面

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

public class SplitPdfExample {
    public static void main(String[] args) {
        try {
            PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            PdfDocument copied = PDF.copyPage(0);
            copied.saveAs("assets/Split.pdf");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;

public class SplitPdfExample {
    public static void main(String[] args) {
        try {
            PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            PdfDocument copied = PDF.copyPage(0);
            copied.saveAs("assets/Split.pdf");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

设置 PDF 文档的自定义尺寸

IronPDF 允许开发人员创建具有非常规尺寸的 PDF 文档,这超出了常规的 A4 尺寸(8½ x 11 英寸或 21.59 x 27.94 厘米)。

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import com.ironsoftware.ironpdf.render.PaperSize;
import java.io.IOException;
import java.nio.file.Paths;

public class CustomSizeExample {
    public static void main(String[] args) {
        String html = "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>";

        ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
        renderOptions.setPaperSize(PaperSize.Custom);

        /*
        * Setting page sizes using different measuring units:
        * 1. setCustomPaperWidth( width ) / setCustomPaperHeight( height ): for inches
        * 2. setCustomPaperSizeInCentimeters( width, height ): for centimeters.
        * 3. setCustomPaperSizeInMillimeters( width, height ): for millimeters
        * 4. setCustomPaperSizeInPixelsOrPoints( width, height ): for pixels/points
        * */
        renderOptions.setCustomPaperSizeInCentimeters(13.97, 13.97);

        PdfDocument.renderHtmlAsPdf(html, renderOptions).saveAs(Paths.get("assets/CustomPaperSize.pdf"));
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import com.ironsoftware.ironpdf.render.PaperSize;
import java.io.IOException;
import java.nio.file.Paths;

public class CustomSizeExample {
    public static void main(String[] args) {
        String html = "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>";

        ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
        renderOptions.setPaperSize(PaperSize.Custom);

        /*
        * Setting page sizes using different measuring units:
        * 1. setCustomPaperWidth( width ) / setCustomPaperHeight( height ): for inches
        * 2. setCustomPaperSizeInCentimeters( width, height ): for centimeters.
        * 3. setCustomPaperSizeInMillimeters( width, height ): for millimeters
        * 4. setCustomPaperSizeInPixelsOrPoints( width, height ): for pixels/points
        * */
        renderOptions.setCustomPaperSizeInCentimeters(13.97, 13.97);

        PdfDocument.renderHtmlAsPdf(html, renderOptions).saveAs(Paths.get("assets/CustomPaperSize.pdf"));
    }
}
JAVA

这里是关于 IronPDF 上 PDF 的自定义尺寸的更多技巧

设置 PDF 方向

Java 的 IronPDF 允许修改新 PDF 和现有 PDF 的页面方向。 默认情况下,使用 IronPDF 创建的新 PDF 设置为纵向,但开发人员可以通过在将内容(如 HTML、RTF 和 URLs)转换为 PDF 时使用 ChromePdfRenderOptions 实例来更改。

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

public class SetOrientationExample {
    public static void main(String[] args) {
        // Load an existing PDF
        PdfDocument existingPdf = PdfDocument.fromFile("assets/sample.pdf");

        // Get the orientation of the first page of the existing PDF document.
        PageRotation firstPageRotation = existingPdf.getPagesInfo().get(0).getPageRotation();
        System.out.println(firstPageRotation);

        // Rotate the first page of the document only 90 degrees clockwise.
        existingPdf.rotatePage(PageRotation.CLOCKWISE_90, PageSelection.firstPage());

        // Rotate all pages of the document clockwise.
        existingPdf.rotateAllPages(PageRotation.CLOCKWISE_270);

        existingPdf.saveAs(Paths.get("assets/ExistingPdfRotated.pdf"));
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.page.PageRotation;
import com.ironsoftware.ironpdf.render.*;
import java.io.IOException;
import java.nio.file.Paths;

public class SetOrientationExample {
    public static void main(String[] args) {
        // Load an existing PDF
        PdfDocument existingPdf = PdfDocument.fromFile("assets/sample.pdf");

        // Get the orientation of the first page of the existing PDF document.
        PageRotation firstPageRotation = existingPdf.getPagesInfo().get(0).getPageRotation();
        System.out.println(firstPageRotation);

        // Rotate the first page of the document only 90 degrees clockwise.
        existingPdf.rotatePage(PageRotation.CLOCKWISE_90, PageSelection.firstPage());

        // Rotate all pages of the document clockwise.
        existingPdf.rotateAllPages(PageRotation.CLOCKWISE_270);

        existingPdf.saveAs(Paths.get("assets/ExistingPdfRotated.pdf"));
    }
}
JAVA

更多信息,请访问 IronPDF 网站上的 设置 PDF 方向教程

设置 PDF 的自定义边距

IronPDF 创建的新 PDF 在四周(顶部、底部、左侧、右侧)的默认边距为 25mm。 然而,开发人员可以使用 IronPDF 以特定测量值自定义每个边距。

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.Paths;

public class CustomMarginsExample {
    public static void main(String[] args) {
        // Set Margins (in millimeters)
        ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
        renderOptions.setMarginTop(40);
        renderOptions.setMarginLeft(20);
        renderOptions.setMarginRight(20);
        renderOptions.setMarginBottom(40);

        try {
            PdfDocument.renderHtmlFileAsPdf("assets/wikipedia.html", renderOptions).saveAs(Paths.get("assets/MyContent.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.Paths;

public class CustomMarginsExample {
    public static void main(String[] args) {
        // Set Margins (in millimeters)
        ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
        renderOptions.setMarginTop(40);
        renderOptions.setMarginLeft(20);
        renderOptions.setMarginRight(20);
        renderOptions.setMarginBottom(40);

        try {
            PdfDocument.renderHtmlFileAsPdf("assets/wikipedia.html", renderOptions).saveAs(Paths.get("assets/MyContent.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

请访问 IronPDF 网站以了解更多关于 设置 PDF 文档自定义边距 的信息。

将 PDF 文档转换为图像

IronPDF 可以将加载的 PDF 文件的页面、转换的源内容或具有页眉、页脚、边距等的修改过的 PDF 导出为可以保存到文件系统、存储在数据库中或通过网络传输的图像。

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

public class ConvertPdfToImagesExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/composite.pdf"));

            // Extract all the pages from the PDF file.
            List<BufferedImage> extractedImages = pdf.toBufferedImages();

            // With the ToImageOptions object, specify maximum image dimensions for each
            // extracted image, as well as their DPI
            ToImageOptions rasterOptions = new ToImageOptions();
            rasterOptions.setImageMaxHeight(100);
            rasterOptions.setImageMaxWidth(100);

            // Call the toBufferedImage method along with a PageSelection object to choose the pages from which to
            // extract the images
            //
            // Available PageSelection methods include: allPages, lastPage, firstPage, singlePage(int pageIndex),
            // and pageRange(int startingPage, int endingPage)
            List<BufferedImage> sizedExtractedImages = pdf.toBufferedImages(rasterOptions, PageSelection.allPages());

            // Save all the extracted images to a file location
            int i = 1;
            for (BufferedImage extractedImage : sizedExtractedImages) {
                String fileName = "assets/images/" + i++ + ".png";
                ImageIO.write(extractedImage, "PNG", new File(fileName));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.image.ToImageOptions;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;

public class ConvertPdfToImagesExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/composite.pdf"));

            // Extract all the pages from the PDF file.
            List<BufferedImage> extractedImages = pdf.toBufferedImages();

            // With the ToImageOptions object, specify maximum image dimensions for each
            // extracted image, as well as their DPI
            ToImageOptions rasterOptions = new ToImageOptions();
            rasterOptions.setImageMaxHeight(100);
            rasterOptions.setImageMaxWidth(100);

            // Call the toBufferedImage method along with a PageSelection object to choose the pages from which to
            // extract the images
            //
            // Available PageSelection methods include: allPages, lastPage, firstPage, singlePage(int pageIndex),
            // and pageRange(int startingPage, int endingPage)
            List<BufferedImage> sizedExtractedImages = pdf.toBufferedImages(rasterOptions, PageSelection.allPages());

            // Save all the extracted images to a file location
            int i = 1;
            for (BufferedImage extractedImage : sizedExtractedImages) {
                String fileName = "assets/images/" + i++ + ".png";
                ImageIO.write(extractedImage, "PNG", new File(fileName));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

添加背景和前景

IronPDF provides addBackgroundPdf and addForegroundPdf methods for adding a specific background or foreground element to PDFs. 这些方法允许开发人员将一个 PDF 的内容作为另一个 PDF 的背景或前景元素进行合并,这对基于通用设计模板的 PDF 集合生成非常高效。

将 PDF 作为背景添加

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

public class AddBackgroundExample {
    public static void main(String[] args) {
        try {
            // Load background PDFs from the filesystem (or create them programmatically)
            PdfDocument backgroundPdf = PdfDocument.fromFile(Paths.get("assets/MyBackground.pdf"));

            // Render content (HTML, URL, etc) as a PDF Document
            PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

            // Add the background PDFs to the newly-rendered document.
            pdf.addBackgroundPdf(backgroundPdf);

            pdf.saveAs(Paths.get("assets/BackgroundPdf.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;

public class AddBackgroundExample {
    public static void main(String[] args) {
        try {
            // Load background PDFs from the filesystem (or create them programmatically)
            PdfDocument backgroundPdf = PdfDocument.fromFile(Paths.get("assets/MyBackground.pdf"));

            // Render content (HTML, URL, etc) as a PDF Document
            PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

            // Add the background PDFs to the newly-rendered document.
            pdf.addBackgroundPdf(backgroundPdf);

            pdf.saveAs(Paths.get("assets/BackgroundPdf.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

将 PDF 作为前景添加

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

public class AddForegroundExample {
    public static void main(String[] args) {
        try {
            PdfDocument foregroundPdf = PdfDocument.fromFile(Paths.get("assets/MyForeground.pdf"));
            PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
            pdf.addForegroundPdf(foregroundPdf);

            pdf.saveAs(Paths.get("assets/BackgroundForegroundPdf.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;

public class AddForegroundExample {
    public static void main(String[] args) {
        try {
            PdfDocument foregroundPdf = PdfDocument.fromFile(Paths.get("assets/MyForeground.pdf"));
            PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");
            pdf.addForegroundPdf(foregroundPdf);

            pdf.saveAs(Paths.get("assets/BackgroundForegroundPdf.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

编辑文档属性

添加和使用 PDF 元数据

IronPDF 提供了修改 PDF 元数据的能力和安全功能,包括将 PDF 设置为只读、不可打印、密码保护和加密。 在 Java 的 IronPDF 中,MetadataManager 可访问和编辑 PDF 的元数据。 MetadataManager 类提供对元数据内容直接访问,并允许开发人员通过具有相同名称的 getter 和 setter 读取和编辑常见的元数据属性。

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

public class EditMetadataExample {
    public static void main(String[] args) {
        try {
            // Open an encrypted file (or create a new one from HTML)
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/encrypted.pdf"), "password");

            // Edit file metadata
            MetadataManager metadata = pdf.getMetadata();
            metadata.setAuthor("Satoshi Nakamoto");
            metadata.setKeywords("SEO, Friendly");
            metadata.setModifiedDate(new Date().toString());

            // Edit file security settings
            // The code below makes the PDF read-only and disallows users to copy, paste, and print
            SecurityOptions securityOptions = new SecurityOptions();
            securityOptions.setAllowUserCopyPasteContent(false);
            securityOptions.setAllowUserAnnotations(false);
            securityOptions.setAllowUserPrinting(PdfPrintSecurity.FULL_PRINT_RIGHTS);
            securityOptions.setAllowUserFormData(false);
            securityOptions.setOwnerPassword("top-secret");
            securityOptions.setUserPassword("sharable");

            // Change or set the document encryption password
            SecurityManager securityManager = pdf.getSecurity();
            securityManager.removePasswordsAndEncryption();
            securityManager.makePdfDocumentReadOnly("secret-key");

            securityManager.setSecurityOptions(securityOptions);
            pdf.saveAs(Paths.get("assets/secured.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.metadata.MetadataManager;
import com.ironsoftware.ironpdf.security.PdfPrintSecurity;
import com.ironsoftware.ironpdf.security.SecurityOptions;
import com.ironsoftware.ironpdf.security.SecurityManager;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Date;

public class EditMetadataExample {
    public static void main(String[] args) {
        try {
            // Open an encrypted file (or create a new one from HTML)
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/encrypted.pdf"), "password");

            // Edit file metadata
            MetadataManager metadata = pdf.getMetadata();
            metadata.setAuthor("Satoshi Nakamoto");
            metadata.setKeywords("SEO, Friendly");
            metadata.setModifiedDate(new Date().toString());

            // Edit file security settings
            // The code below makes the PDF read-only and disallows users to copy, paste, and print
            SecurityOptions securityOptions = new SecurityOptions();
            securityOptions.setAllowUserCopyPasteContent(false);
            securityOptions.setAllowUserAnnotations(false);
            securityOptions.setAllowUserPrinting(PdfPrintSecurity.FULL_PRINT_RIGHTS);
            securityOptions.setAllowUserFormData(false);
            securityOptions.setOwnerPassword("top-secret");
            securityOptions.setUserPassword("sharable");

            // Change or set the document encryption password
            SecurityManager securityManager = pdf.getSecurity();
            securityManager.removePasswordsAndEncryption();
            securityManager.makePdfDocumentReadOnly("secret-key");

            securityManager.setSecurityOptions(securityOptions);
            pdf.saveAs(Paths.get("assets/secured.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

数字签名

Java 的 IronPDF 允许使用 X509Certificate2 数字证书(.pfx 或 .p12 格式)安全地对新 PDF 或现有 PDF 文件进行签名。 通过数字签名 PDF,确保其真实性,并防止未经证书验证进行的更改。 这增强了文档的可靠性。

要生成签名证书的免费方式,Adobe Reader 在其数字 ID 教程中提供 说明

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.signature.Signature;
import com.ironsoftware.ironpdf.signature.SignatureManager;

public class DigitalSignatureExample {
    public static void main(String[] args) {
        try {
            PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));

            // Load the X509Certificate2 digitals certificates from .pfx or .p12 formats
            File path = new File("assets/Ironpdf.pfx");
            byte[] certificate = new byte[(int) path.length()];

            // Sign PDF with a specific signature
            Signature signature = new Signature(certificate, "1234");
            SignatureManager manager = PDF.getSignature();
            manager.signPdfWithSignature(signature);

            PDF.saveAs(Paths.get("assets/signed_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.signature.Signature;
import com.ironsoftware.ironpdf.signature.SignatureManager;

public class DigitalSignatureExample {
    public static void main(String[] args) {
        try {
            PdfDocument PDF = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));

            // Load the X509Certificate2 digitals certificates from .pfx or .p12 formats
            File path = new File("assets/Ironpdf.pfx");
            byte[] certificate = new byte[(int) path.length()];

            // Sign PDF with a specific signature
            Signature signature = new Signature(certificate, "1234");
            SignatureManager manager = PDF.getSignature();
            manager.signPdfWithSignature(signature);

            PDF.saveAs(Paths.get("assets/signed_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

压缩 PDF

IronPDF reduces PDF file size with its compressImages method in the PdfDocument class, making it easy to compress PDFs with large images. 这种优化在电子邮件和其他通讯渠道传输 PDF 时带来显著的存储空间和成本节省。

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

public class CompressPdfExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/document.pdf"));

            // Valid image compression values range from 1 to 100, where 100 represents 100% of the original image quality.
            pdf.compressImages(60);
            pdf.saveAs(Paths.get("assets/document_compressed.pdf"));

            // The second, optional parameter can scale down the image resolution according to its visible size in the PDF document.
            // Note that this may cause distortion with some image configurations.
            pdf.compressImages(90, true);
            pdf.saveAs(Paths.get("assets/document_scaled_compressed.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;

public class CompressPdfExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/document.pdf"));

            // Valid image compression values range from 1 to 100, where 100 represents 100% of the original image quality.
            pdf.compressImages(60);
            pdf.saveAs(Paths.get("assets/document_compressed.pdf"));

            // The second, optional parameter can scale down the image resolution according to its visible size in the PDF document.
            // Note that this may cause distortion with some image configurations.
            pdf.compressImages(90, true);
            pdf.saveAs(Paths.get("assets/document_scaled_compressed.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

编辑 PDF 内容

添加页眉和页脚

IronPDF allows you to add custom HTML headers and footers using the ChromePdfRenderOptions and HtmlHeaderFooter classes. It also supports custom text headers and footers through the TextHeaderFooter class, which allows specifying text for the header/footer's left, right, or center regions. 模板标签如 {date}、{time} 和 {page} 可与自定义文本一起使用。

HTML 页眉和页脚

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.headerfooter.HtmlHeaderFooter;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class HtmlHeaderFooterExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

            // Build a footer using HTML
            // Merge Fields are: {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
            HtmlHeaderFooter footer = new HtmlHeaderFooter();
            footer.setMaxHeight(15); // millimeters
            footer.setHtmlFragment("<center><i>{page} of {total-pages}</i></center>");
            footer.setDrawDividerLine(true);
            pdf.addHtmlFooter(footer);
            List<PdfDocument> pdfs = new ArrayList<>();

            // Build a header using an image asset
            // Note the use of BaseUrl to set a relative path to the assets
            HtmlHeaderFooter header = new HtmlHeaderFooter();
            header.setMaxHeight(20); // millimeters
            header.setHtmlFragment("<img src=\"logo.png\" />");
            header.setBaseUrl("./assets/");
            pdf.addHtmlHeader(header);

            pdf.saveAs(Paths.get("assets/html_headers_footers.pdf"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.headerfooter.HtmlHeaderFooter;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class HtmlHeaderFooterExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

            // Build a footer using HTML
            // Merge Fields are: {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
            HtmlHeaderFooter footer = new HtmlHeaderFooter();
            footer.setMaxHeight(15); // millimeters
            footer.setHtmlFragment("<center><i>{page} of {total-pages}</i></center>");
            footer.setDrawDividerLine(true);
            pdf.addHtmlFooter(footer);
            List<PdfDocument> pdfs = new ArrayList<>();

            // Build a header using an image asset
            // Note the use of BaseUrl to set a relative path to the assets
            HtmlHeaderFooter header = new HtmlHeaderFooter();
            header.setMaxHeight(20); // millimeters
            header.setHtmlFragment("<img src=\"logo.png\" />");
            header.setBaseUrl("./assets/");
            pdf.addHtmlHeader(header);

            pdf.saveAs(Paths.get("assets/html_headers_footers.pdf"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
JAVA

文本页眉和页脚

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

public class TextHeaderFooterExample {
    public static void main(String[] args) {
        try {
            // Initialize HeaderFooterOptions object.
            HeaderFooterOptions options = new HeaderFooterOptions();
            PdfDocument pdf = PdfDocument.renderUrlAsPdf("http://www.google.com");

            // Add a header to every page easily
            // Mergeable fields are:
            // {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
            options.setFirstPageNumber(1); // use 2 if a coverpage will be appended
            TextHeaderFooter textHeader = new TextHeaderFooter();
            textHeader.setDrawDividerLine(true);
            textHeader.setCenterText("{url}");
            textHeader.setFont(FontTypes.getHelvetica());
            textHeader.setFontSize(12);
            pdf.addTextHeader(textHeader, options);

            // Add a footer too
            TextHeaderFooter textFooter = new TextHeaderFooter();
            textFooter.setDrawDividerLine(true);
            textFooter.setFont(FontTypes.getArial());
            textFooter.setFontSize(10);
            textFooter.setLeftText("{date} {time}");
            textFooter.setRightText("{page} of {total-pages}");
            pdf.addTextFooter(textFooter, options);

            pdf.saveAs(Paths.get("assets/text_headers_footers.pdf"));
        } catch (IOException e) {
            System.out.println("Failed to save PDF");
            throw new RuntimeException(e);
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.font.FontTypes;
import com.ironsoftware.ironpdf.headerfooter.TextHeaderFooter;
import com.ironsoftware.ironpdf.headerfooter.HeaderFooterOptions;
import java.io.IOException;
import java.nio.file.Paths;

public class TextHeaderFooterExample {
    public static void main(String[] args) {
        try {
            // Initialize HeaderFooterOptions object.
            HeaderFooterOptions options = new HeaderFooterOptions();
            PdfDocument pdf = PdfDocument.renderUrlAsPdf("http://www.google.com");

            // Add a header to every page easily
            // Mergeable fields are:
            // {page} {total-pages} {url} {date} {time} {html-title} & {pdf-title}
            options.setFirstPageNumber(1); // use 2 if a coverpage will be appended
            TextHeaderFooter textHeader = new TextHeaderFooter();
            textHeader.setDrawDividerLine(true);
            textHeader.setCenterText("{url}");
            textHeader.setFont(FontTypes.getHelvetica());
            textHeader.setFontSize(12);
            pdf.addTextHeader(textHeader, options);

            // Add a footer too
            TextHeaderFooter textFooter = new TextHeaderFooter();
            textFooter.setDrawDividerLine(true);
            textFooter.setFont(FontTypes.getArial());
            textFooter.setFontSize(10);
            textFooter.setLeftText("{date} {time}");
            textFooter.setRightText("{page} of {total-pages}");
            pdf.addTextFooter(textFooter, options);

            pdf.saveAs(Paths.get("assets/text_headers_footers.pdf"));
        } catch (IOException e) {
            System.out.println("Failed to save PDF");
            throw new RuntimeException(e);
        }
    }
}
JAVA

书签

With the BookmarkManager class, developers can create a hierarchical structure of bookmarks within a PDF, allowing users to easily navigate to different sections. 要添加新书签,使用 add 方法,指定书签的标题和页码。 书签可以嵌套以创建更有组织的结构。

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

public class BookmarksExample {
    public static void main(String[] args) {
        try {
            // Load an existing PDF from the file system (or create a new one from HTML)
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/book.pdf"));

            // Add top-level bookmarks to pages of the PDF using their page indices
            BookmarkManager bookmarks = pdf.getBookmark();
            bookmarks.addBookMarkAtEnd("Author's Note", 2);
            bookmarks.addBookMarkAtEnd("Table of Contents", 3);
            bookmarks.addBookMarkAtEnd("Summary", 10);
            bookmarks.addBookMarkAtEnd("References", 12);

            // Retrieve a reference to the Summary bookmark so that we can add a sublist of bookmarks to it.
            List<Bookmark> bookmarkList = bookmarks.getBookmarks();
            Bookmark bookmark = bookmarkList.get(2);
            bookmark.addChildBookmark("Conclusion", 11);

            // Save the PDF to the filesystem
            pdf.saveAs(Paths.get("assets/bookmarked.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.bookmark.Bookmark;
import com.ironsoftware.ironpdf.bookmark.BookmarkManager;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;

public class BookmarksExample {
    public static void main(String[] args) {
        try {
            // Load an existing PDF from the file system (or create a new one from HTML)
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/book.pdf"));

            // Add top-level bookmarks to pages of the PDF using their page indices
            BookmarkManager bookmarks = pdf.getBookmark();
            bookmarks.addBookMarkAtEnd("Author's Note", 2);
            bookmarks.addBookMarkAtEnd("Table of Contents", 3);
            bookmarks.addBookMarkAtEnd("Summary", 10);
            bookmarks.addBookMarkAtEnd("References", 12);

            // Retrieve a reference to the Summary bookmark so that we can add a sublist of bookmarks to it.
            List<Bookmark> bookmarkList = bookmarks.getBookmarks();
            Bookmark bookmark = bookmarkList.get(2);
            bookmark.addChildBookmark("Conclusion", 11);

            // Save the PDF to the filesystem
            pdf.saveAs(Paths.get("assets/bookmarked.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

添加和编辑注释

IronPDF can add "sticky note" style annotations to specific pages of a PDF using the AnnotationManager and AnnotationOptions classes. 通过为 AnnotationOptions 构造函数提供文本和 (x, y) 坐标创建基于文本的注释,然后使用 addTextAnnotation 方法将注释添加到所需页面。

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.annotation.AnnotationIcon;
import com.ironsoftware.ironpdf.annotation.AnnotationManager;
import com.ironsoftware.ironpdf.annotation.AnnotationOptions;
import java.io.IOException;
import java.nio.file.Paths;

public class AnnotationExample {
    public static void main(String[] args) {
        try {
            // Create a new PDF or load an existing one from the filesystem
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/example.pdf"));

            // Create an annotation to be placed at a specific location on a page.
            AnnotationOptions annotation = new AnnotationOptions(
                    "This is a major title",                            // Title of the annotation
                    "This is the long 'sticky note' comment content...", // Content of the annotation
                    150,                                                // x-axis coordinate location
                    250                                                 // y-axis coordinate location
            );
            annotation.setIcon(AnnotationIcon.HELP);
            annotation.setOpacity(0.9);
            annotation.setPrintable(false);
            annotation.setHidden(false);
            annotation.setOpen(true);
            annotation.setReadonly(true);
            annotation.setRotateable(true);

            // Add the annotation to a specific page of the PDF
            AnnotationManager annotationManager = pdf.getAnnotation();
            annotationManager.addTextAnnotation(annotation, 0);

            // Save the PDF with the modifications
            pdf.saveAs(Paths.get("assets/annotated.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.annotation.AnnotationIcon;
import com.ironsoftware.ironpdf.annotation.AnnotationManager;
import com.ironsoftware.ironpdf.annotation.AnnotationOptions;
import java.io.IOException;
import java.nio.file.Paths;

public class AnnotationExample {
    public static void main(String[] args) {
        try {
            // Create a new PDF or load an existing one from the filesystem
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/example.pdf"));

            // Create an annotation to be placed at a specific location on a page.
            AnnotationOptions annotation = new AnnotationOptions(
                    "This is a major title",                            // Title of the annotation
                    "This is the long 'sticky note' comment content...", // Content of the annotation
                    150,                                                // x-axis coordinate location
                    250                                                 // y-axis coordinate location
            );
            annotation.setIcon(AnnotationIcon.HELP);
            annotation.setOpacity(0.9);
            annotation.setPrintable(false);
            annotation.setHidden(false);
            annotation.setOpen(true);
            annotation.setReadonly(true);
            annotation.setRotateable(true);

            // Add the annotation to a specific page of the PDF
            AnnotationManager annotationManager = pdf.getAnnotation();
            annotationManager.addTextAnnotation(annotation, 0);

            // Save the PDF with the modifications
            pdf.saveAs(Paths.get("assets/annotated.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

盖章和水印

IronPDF for Java 提供一个强大的 API,提供广泛的盖章和水印功能。 使用其易于使用的界面,开发人员可以快速将图像和 HTML 章添加到他们的 PDF。 无论您是需要公司徽标、保密声明还是唯一标识符,IronPDF 均能满足您的需求,使您能够轻松专业地在 PDF 上添加章。

将文本盖章到 PDF 上

import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.TextStamper;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;

public class StampTextExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            TextStamper stamper1 = new TextStamper();
            stamper1.setText("Hello World! Stamp One Here!");
            stamper1.setFontFamily("Bungee Spice");
            stamper1.setUseGoogleFont(true);

            stamper1.setFontSize(100);
            stamper1.setBold(true);
            stamper1.setItalic(false);
            stamper1.setVerticalAlignment(VerticalAlignment.TOP);

            pdf.applyStamp(stamper1);
            pdf.saveAs(Paths.get("assets/stamped_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.TextStamper;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;

public class StampTextExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            TextStamper stamper1 = new TextStamper();
            stamper1.setText("Hello World! Stamp One Here!");
            stamper1.setFontFamily("Bungee Spice");
            stamper1.setUseGoogleFont(true);

            stamper1.setFontSize(100);
            stamper1.setBold(true);
            stamper1.setItalic(false);
            stamper1.setVerticalAlignment(VerticalAlignment.TOP);

            pdf.applyStamp(stamper1);
            pdf.saveAs(Paths.get("assets/stamped_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

将图像盖章到 PDF 上

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

public class StampImageExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            ImageStamper imageStamper = new ImageStamper(Paths.get("assets/logo.png"));
            // Apply to every page, one page, or some pages
            pdf.applyStamp(imageStamper);
            pdf.applyStamp(imageStamper, PageSelection.singlePage(2));
            pdf.applyStamp(imageStamper, PageSelection.pageRange(0, 2));
            pdf.saveAs(Paths.get("assets/image_stamped_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.edit.PageSelection;
import com.ironsoftware.ironpdf.stamp.ImageStamper;

public class StampImageExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            ImageStamper imageStamper = new ImageStamper(Paths.get("assets/logo.png"));
            // Apply to every page, one page, or some pages
            pdf.applyStamp(imageStamper);
            pdf.applyStamp(imageStamper, PageSelection.singlePage(2));
            pdf.applyStamp(imageStamper, PageSelection.pageRange(0, 2));
            pdf.saveAs(Paths.get("assets/image_stamped_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

将条形码盖章到 PDF 上

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

public class StampBarcodeExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            BarcodeStamper barcodeStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.Code39);

            barcodeStamp.setHorizontalAlignment(HorizontalAlignment.LEFT);
            barcodeStamp.setVerticalAlignment(VerticalAlignment.BOTTOM);

            pdf.applyStamp(barcodeStamp);
            pdf.saveAs(Paths.get("assets/barcode_stamped_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.BarcodeEncoding;
import com.ironsoftware.ironpdf.stamp.BarcodeStamper;
import com.ironsoftware.ironpdf.stamp.HorizontalAlignment;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;

public class StampBarcodeExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            BarcodeStamper barcodeStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.Code39);

            barcodeStamp.setHorizontalAlignment(HorizontalAlignment.LEFT);
            barcodeStamp.setVerticalAlignment(VerticalAlignment.BOTTOM);

            pdf.applyStamp(barcodeStamp);
            pdf.saveAs(Paths.get("assets/barcode_stamped_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

将 QR 码盖章到 PDF 上

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

public class StampQrCodeExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            BarcodeStamper QRStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.QRCode);
            QRStamp.setHeight(50);
            QRStamp.setWidth(50);
            QRStamp.setHorizontalAlignment(HorizontalAlignment.LEFT);
            QRStamp.setVerticalAlignment(VerticalAlignment.BOTTOM);
            pdf.applyStamp(QRStamp);
            pdf.saveAs(Paths.get("assets/qrcode_stamped_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.stamp.BarcodeEncoding;
import com.ironsoftware.ironpdf.stamp.BarcodeStamper;
import com.ironsoftware.ironpdf.stamp.HorizontalAlignment;
import com.ironsoftware.ironpdf.stamp.VerticalAlignment;

public class StampQrCodeExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            BarcodeStamper QRStamp = new BarcodeStamper("IronPDF", BarcodeEncoding.QRCode);
            QRStamp.setHeight(50);
            QRStamp.setWidth(50);
            QRStamp.setHorizontalAlignment(HorizontalAlignment.LEFT);
            QRStamp.setVerticalAlignment(VerticalAlignment.BOTTOM);
            pdf.applyStamp(QRStamp);
            pdf.saveAs(Paths.get("assets/qrcode_stamped_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

将水印添加到 PDF 上

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

public class AddWatermarkExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            String html = "<h1> Example Title <h1/>";
            int watermarkOpacity = 30;
            pdf.applyWatermark(html, watermarkOpacity);
            pdf.saveAs(Paths.get("assets/watermarked_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.IOException;
import java.nio.file.Paths;
import com.ironsoftware.ironpdf.PdfDocument;

public class AddWatermarkExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.fromFile(Paths.get("assets/sample.pdf"));
            String html = "<h1> Example Title <h1/>";
            int watermarkOpacity = 30;
            pdf.applyWatermark(html, watermarkOpacity);
            pdf.saveAs(Paths.get("assets/watermarked_sample.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

在 PDF 中使用表单

IronPDF Java 为在 PDF 文档中使用 FormManager 类设置和检索表单文本字段的值提供了一种简单高效的方法。 开发人员可以调用 setFieldValue 方法提供文本字段名称和值。

通过使用相关名称或索引,通过 FormManagerFormField 对象集合直接检索表单字段的值。 这种对表单字段的控制使处理动态和交互式 PDF 表单变得容易。

创建和编辑表单

import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.Paths;

public class CreateAndEditFormsExample {
    public static void main(String[] args) {
        try {
            // #1 Use Case: Create a PDF Form from HTML Form Markup
            Path outputLocation = Paths.get("assets/BasicForm.pdf");
            String formHTML = "<html>" +
                    "<body>" +
                    "<h2>Editable PDF Form</h2>" +
                    "<form>" +
                    "First name: <br> <input type='text' name='firstname' value=''> <br>" +
                    "Last name: <br> <input type='text' name='lastname' value=''>" +
                    "</form>" +
                    "</body>" +
                    "</html>";

            ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
            renderOptions.setCreatePdfFormsFromHtml(true);
            PdfDocument.renderHtmlAsPdf(formHTML, renderOptions).saveAs(outputLocation);

            // #2 Use Case: Writing Values to the PDF Form
            PdfDocument form = PdfDocument.fromFile(outputLocation);

            // Set the value of the firstname input field.
            form.getForm().setFieldValue("firstname", "Minnie");

            // Set the value of the lastname input field.
            form.getForm().setFieldValue("lastname", "Mouse");

            // Save the changes to the PDF Form.
            form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;
import java.io.IOException;
import java.nio.file.Paths;

public class CreateAndEditFormsExample {
    public static void main(String[] args) {
        try {
            // #1 Use Case: Create a PDF Form from HTML Form Markup
            Path outputLocation = Paths.get("assets/BasicForm.pdf");
            String formHTML = "<html>" +
                    "<body>" +
                    "<h2>Editable PDF Form</h2>" +
                    "<form>" +
                    "First name: <br> <input type='text' name='firstname' value=''> <br>" +
                    "Last name: <br> <input type='text' name='lastname' value=''>" +
                    "</form>" +
                    "</body>" +
                    "</html>";

            ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();
            renderOptions.setCreatePdfFormsFromHtml(true);
            PdfDocument.renderHtmlAsPdf(formHTML, renderOptions).saveAs(outputLocation);

            // #2 Use Case: Writing Values to the PDF Form
            PdfDocument form = PdfDocument.fromFile(outputLocation);

            // Set the value of the firstname input field.
            form.getForm().setFieldValue("firstname", "Minnie");

            // Set the value of the lastname input field.
            form.getForm().setFieldValue("lastname", "Mouse");

            // Save the changes to the PDF Form.
            form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

填充现有表单

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

public class FillExistingFormsExample {
    public static void main(String[] args) {
        try {
            PdfDocument form = PdfDocument.fromFile("assets/pdfform.pdf");

            // Set the value of the firstname input field.
            form.getForm().setFieldValue("firstname", "Minnie");

            // Set the value of the lastname input field.
            form.getForm().setFieldValue("lastname", "Mouse");

            // Save the changes to the PDF Form.
            form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.io.IOException;
import java.nio.file.Paths;

public class FillExistingFormsExample {
    public static void main(String[] args) {
        try {
            PdfDocument form = PdfDocument.fromFile("assets/pdfform.pdf");

            // Set the value of the firstname input field.
            form.getForm().setFieldValue("firstname", "Minnie");

            // Set the value of the lastname input field.
            form.getForm().setFieldValue("lastname", "Mouse");

            // Save the changes to the PDF Form.
            form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
JAVA

发送 PDF 进行打印

IronPDF 的打印方法允许开发人员轻松将 PDF 打印 集成到其应用程序中。 通过调用 [print](/java/object-reference/api/com/ironsoftware/ironpdf/PdfDocument.html#print()) 方法,操作系统的打印对话框将打开,提供用户调整设置(如打印机、纸张尺寸和副本数量)的选项。

import com.ironsoftware.ironpdf.PdfDocument;
import java.awt.print.PrinterException;

public class PrintPdfExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Created with IronPDF!</h1>");
            pdf.print();
        } catch (PrinterException exception) {
            System.out.println("Failed to print PDF");
            exception.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
import com.ironsoftware.ironpdf.PdfDocument;
import java.awt.print.PrinterException;

public class PrintPdfExample {
    public static void main(String[] args) {
        try {
            PdfDocument pdf = PdfDocument.renderHtmlAsPdf("<h1>Created with IronPDF!</h1>");
            pdf.print();
        } catch (PrinterException exception) {
            System.out.println("Failed to print PDF");
            exception.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
JAVA

结论

IronPDF 是 Java 的综合 PDF 库,提供广泛的功能用于创建、编辑和处理 PDF 文档。 它具有强大的文本和图像提取方法,允许开发人员访问和处理 PDF 内容。 IronPDF 还提供在自定义 PDF 元数据和安全设置方面的灵活性,例如将 PDF 设置为只读或密码保护。 它包含一种压缩 PDF 的方法,减少文件大小,并提高传输效率。

该库允许向 PDF 文档添加自定义页眉和页脚以及注释。 书签功能使开发人员可以添加书签以便在 PDF 中轻松导航。

IronPDF 提供一个免费试用密钥,让用户可以在购买之前测试其功能和实现能力。 IronPDF Java 许可证 起价为 $799,为希望保护和管理其 pdf 文件的企业和个人提供了一种经济有效的解决方案。

常见问题解答

Java PDF 编辑器库的主要功能是什么?

Java PDF 编辑器库提供全面的编辑和创建 PDF 工具,包括添加签名、HTML 页脚、水印和注释。它还支持合并和拆分 PDF,自定义尺寸和方向,以及将 PDF 转换为图像。

如何将 PDF 库集成到我的 Java 项目中?

要将像 IronPDF 这样的 PDF 库集成到您的 Java 项目中,请从 IronPDF 官方网站下载该库,并将其添加为您项目构建配置中的依赖项。

如何在 Java 中修改 PDF 文档的结构?

您可以在 Java 中使用 IronPDF 修改 PDF 文档的结构。利用 prependPdfcopyPagesremovePages 方法来添加、复制和删除页面。

是否可以为 PDF 设置自定义边距和元数据?

是的,IronPDF 允许您设置自定义边距并修改 PDF 元数据,包括作者和关键词,使用 MetadataManager 类。

我可以使用 Java 将 PDF 文档转换为图像格式吗?

使用 IronPDF,您可以使用 toBufferedImages 方法将 PDF 页面转换为图像格式,您可以定义图像尺寸和 DPI。

如何添加自定义水印到 PDF 文件?

要向 PDF 文件添加自定义水印,请使用 IronPDF 的 applyWatermark 方法。您可以指定水印内容,如 HTML,并调整其不透明度。

IronPDF 是否支持 PDF 文档的密码保护?

是的,IronPDF 支持密码保护,允许您通过防止未经授权的访问和更改来保护文档。

在 Java 中处理 PDF 表单有哪些工具可用?

IronPDF 提供一个 FormManager 类,用于创建、编辑和填写 PDF 表单。它有助于设置和检索表单字段的值。

如何通过 PDF 中的数字签名确保文档安全?

IronPDF 使用 X509Certificate2 数字证书实现 PDF 文档的安全签名,确保真实性并防止未经授权的更改。

是否可以压缩 PDF 文件以减小其大小?

IronPDF 包括压缩 PDF 文件的方法,这有助于在保持文档质量的同时减少文件大小。

Darrius Serrant
全栈软件工程师(WebOps)

Darrius Serrant 拥有迈阿密大学的计算机科学学士学位,目前在 Iron Software 担任全栈 WebOps 市场工程师。从小就被编码吸引,他认为计算机既神秘又易于接触,使其成为创意和问题解决的理想媒介。

在 Iron Software,Darrius 喜欢创造新事物,并简化复杂概念以使其更易理解。作为我们常驻的开发者之一,他还自愿教授学生,与下一代分享他的专业知识。

对于 Darrius 来说,他的工作令人满意,因为它被重视并产生真正的影响。