tech.chakapoko.com
Home / Java / Apache PDFBox

[Java]PDFBoxで画像を表示する

package com.example;

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;

import java.io.File;
import java.io.IOException;

public class PDFBoxExample {

    public static void main(String[] args) throws IOException {
        try (PDDocument pdDocument = new PDDocument()) {
            PDPage pdPage = new PDPage();

            pdDocument.addPage(pdPage);

            try (PDPageContentStream stream = new PDPageContentStream(pdDocument, pdPage)) {
                String file = new File("java.png").getPath();
                PDImageXObject image = PDImageXObject.createFromFile(file, pdDocument);
                float x = 0f;
                float y = 0f;
                stream.drawImage(image, x, y);
            }

            pdDocument.save(new File("Example.pdf"));
        }
    }

}

draw-an-image.png