Java如何使用Java向PDF文件頁面中新增圖片?

2019-10-16 22:28:52

在Java程式設計中,如何使用Java向PDF文件頁面中新增圖片?

以下是使用Java向PDF文件頁面中新增圖片的範例程式。

package com.yiibai;

import java.io.File;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

public class InsertingImageInPdf {
    public static void main(String args[]) throws Exception {
        PDDocument document = new PDDocument();
        // Add an empty page to it
        document.addPage(new PDPage());

        // Saving the document
        document.save("F:/worksp/javaexamples/java_apache_pdf_box/InsertImage_IP.pdf");
        // Loading an existing document
        File file = new File("F:/worksp/javaexamples/java_apache_pdf_box/InsertImage_IP.pdf");
        PDDocument doc = PDDocument.load(file);

        // Retrieving the page
        PDPage page = doc.getPage(0);

        // Creating PDImageXObject object
        PDImageXObject pdImage = PDImageXObject.createFromFile("F:/worksp/javaexamples/java_apache_pdf_box/logo.png", doc);

        // creating the PDPageContentStream object
        PDPageContentStream contents = new PDPageContentStream(doc, page);

        // Drawing the image in the PDF document
        contents.drawImage(pdImage, 70, 250);
        System.out.println("Image inserted");

        // Closing the PDPageContentStream object
        contents.close();

        // Saving the document
        doc.save("F:/worksp/javaexamples/java_apache_pdf_box/InsertImage_OP.pdf");

        // Closing the document
        doc.close();
    }
}

執行上面範例程式碼,得到以下結果 -

Image inserted

此時,程式已經建立一個新檔案:F:/worksp/javaexamples/java_apache_pdf_box/InsertImage_OP.pdf

開啟這個檔案如下所示 -