如何使用Java在PDF中插入图像。(How to insert image in a PDF using Java.)
优质
小牛编辑
126浏览
2023-12-01
问题描述 (Problem Description)
如何使用Java在PDF中插入图像。
解决方案 (Solution)
以下是使用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();
}
}