[英]PDF Document is only half in width when converted a png image to pdf using PDFBox
[英]Insert image a jpg file into a PDF document using Java pdfbox only 1/4 of image show up in the PDF document
我正在嘗試使用 Java PDFBox 庫將寬度為 1680、高度為 1080 的 jpg 文件插入到 PDF 文檔中。 我試圖在文檔的 20,20 處插入圖像,並且只有 1/4 的圖像顯示在 PDF 中。 我需要將多個圖像和每個圖像插入一個單獨的頁面。 這是我的代碼,請告訴我我做錯了什么?
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.