简体   繁体   English

使用 Java pdfbox 仅将图像的 1/4 显示在 PDF 文档中的 PDF 文档中

[英]Insert image a jpg file into a PDF document using Java pdfbox only 1/4 of image show up in the PDF document

I am trying to insert a jpg file 1680 in width and 1080 in height into a PDF document using Java PDFBox library.我正在尝试使用 Java PDFBox 库将宽度为 1680、高度为 1080 的 jpg 文件插入到 PDF 文档中。 I am trying to insert the image at 20,20 of the document and only 1/4 of image show up in the PDF.我试图在文档的 20,20 处插入图像,并且只有 1/4 的图像显示在 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM