在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
。
打开这个文件如下所示 -