如何在 JAVA 中以编程方式编辑现有 PDF 的内容

How to edit the contents of an existing PDF programmatically in JAVA

假设我有一个现有的 pdf,带有固定的页眉和页脚以及空白正文,如下图所示

然后我要给正文添加内容(图中的白色部分)

我如何在 java 中做到这一点?

使用 iText 的 PdfReader 和 PdfWriter,您可以加载 PDF 文件,进行一些修改,然后将其写入另一个位置。

示例代码:

    String srcPdf = "source-path.pdf";
    String destPdf = "destination-path.pdf";

    PdfReader reader = new PdfReader(srcPdf);
    PdfWriter writer = new PdfWriter(destPdf);

    try (PdfDocument pdfDocument = new PdfDocument(reader, writer)) {

        PdfPage page = pdfDocument.getPage(1);

        // change pdf file starts here
        String imgPath = "image-path.jpg";
        ImageData imageData = ImageDataFactory.create(imgPath);

        // create page canvas
        PdfCanvas pdfCanvas = new PdfCanvas(page);

        // create AT
        AffineTransform at = AffineTransform.getTranslateInstance(page.getPageSize().getWidth() / 10, page.getPageSize().getHeight() / 10);
        at.concatenate(AffineTransform.getScaleInstance(page.getPageSize().getWidth() * 8 / 10, page.getPageSize().getHeight() * 8 / 10));

        float[] matrix = new float[6];
        at.getMatrix(matrix);

        // add image data
        pdfCanvas.addImageWithTransformationMatrix(imageData, matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);

        pdfCanvas.release();
    }
    PdfReader reader = new PdfReader("./the-pdf-where-you-want-to-insert-into.pdf");
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("./destination.pdf"));

    PdfReader r = new PdfReader("./the-pdf-you-want-to-insert.pdf");
    PdfImportedPage page = stamper.getImportedPage(r, 1);

    Image instance = Image.getInstance(page);

    AffineTransform at = AffineTransform.getTranslateInstance(x, y); // x y positions where you want insert
    at.concatenate(AffineTransform.getScaleInstance(instance.getScaledWidth(), instance.getScaledHeight()));

    PdfContentByte canvas = stamper.getOverContent(1);
    canvas.addImage(instance, at);

    stamper.close();
    reader.close();