Javaexamples-insert-image-in-pdf

提供:Dev Guides
移動先:案内検索

Javaの例-PDFに画像を挿入

問題の説明

Javaを使用してPDFに画像を挿入する方法。

溶液

以下は、Javaを使用してPDFに画像を挿入するプログラムの例です。

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 {

     //Loading an existing document
      File file = new File("C:/pdfBox/InsertImage_IP.pdf");
      PDDocument doc = PDDocument.load(file);

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

     //Creating PDImageXObject object
      PDImageXObject pdImage = PDImageXObject.createFromFile("C:/pdfBox/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("C:/pdfBox/InsertImage_OP.pdf");

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

入力

画像入力の挿入

出力

画像出力の挿入