我正在尝试使用Java PDFBox库将宽度为1680,高度为1080的jpg文件插入PDF文档。我正在尝试在文档的20,20处插入图像,而PDF中仅显示图像的1/4。我需要将多个图像和每个图像插入一个单独的页面。这是我的代码,请告诉我我做错了什么?
import java.io.IOException;
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 pdfAddingPages {
public static void main(String[] args) {
//Creating PDF document object
PDDocument document = new PDDocument();
PDPage Page1 = new PDPage();
//Adding the blank page to the document
document.addPage( Page1 );
//Creating PDImageXObject object
PDImageXObject pdImage = null;
try {
pdImage = PDImageXObject.createFromFile("C:/Test/image1680x1080.jpeg",document);
} catch (IOException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
}
//creating the PDPageContentStream object
PDPageContentStream contents;
try {
contents = new PDPageContentStream(document, Page1);
contents.drawImage(pdImage, 20, 20); // positon at 20,20
//contents.drawImage(pdImage, 0, 0, 1638, 1080);
contents.close();
//int chartWidth = 1638; //2000, 1900, 1800
//int chartHeight = 1080 ;
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
//Saving the document
try {
document.save("C:/Test/my_doc_image.pdf");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("PDF created");
//Closing the document
try {
document.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
要以较小的尺寸绘制图像,请使用比例因子:
contents.drawImage(pdImage, 20, 20, pdImage.getWidth() / 4, pdImage.getHeight() / 4);