I am trying to insert a jpg file 1680 in width and 1080 in height into a PDF document using Java PDFBox library. I am trying to insert the image at 20,20 of the document and only 1/4 of image show up in the PDF. I need to insert multiple images and each image into a separate page. Here is my code, please tell me what I did wrong?
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();
}
}
}
to draw the image at a smaller size, use a scale factor:
contents.drawImage(pdImage, 20, 20, pdImage.getWidth() / 4, pdImage.getHeight() / 4);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.