Aspose PDF: Add an image on PDF

Hi,

I’m using Aspose to create a PDF file and add images.

Here is the code I’m using:

try(Document documentPDF = new Document())
{
Page pageJPG;
com.aspose.pdf.Image imageJPG;

		for (final String image : imageList) {
			pageJPG = documentPDF.getPages().add();
			imageJPG = new com.aspose.pdf.Image();
			imageJPG.setFile(folder + File.separator + image + "_temp.jpg");
			pageJPG.getPageInfo().getMargin().setBottom(0);
			pageJPG.getPageInfo().getMargin().setTop(0);
			pageJPG.getPageInfo().getMargin().setRight(0);
			pageJPG.getPageInfo().getMargin().setLeft(0);
			pageJPG.getParagraphs().add(imageJPG);
		}

		documentPDF.save(folder + File.separator + outputPDF);
	}

The thing that for some input images, the result in the PDF is not good. The image is resized.

chq.jpg (78.3 KB)
chq.pdf (94.8 KB)

Do you know how to do to make the Image in the PDF has its original size ?

Thanks a lot

You can find the input image (chq.jpg), and the result with the current code (chp.pdf).

@vfiot

You need to set Height/Width of the page according to the image dimensions like in the below code snippet:

BufferedImage readImage = null;

try {
 readImage = ImageIO.read(new File(dataDir + "chq.jpg"));
 int h = readImage.getHeight();
 int w = readImage.getWidth();
 Document doc = new Document();
 Page page = doc.getPages().add();
 com.aspose.pdf.Image image = new Image();
 image.setFile(dataDir + "chq.jpg");
 page.getPageInfo().setHeight(h);
 page.getPageInfo().setWidth(w);
 page.getPageInfo().getMargin().setBottom(0);
 page.getPageInfo().getMargin().setTop(0);
 page.getPageInfo().getMargin().setRight(0);
 page.getPageInfo().getMargin().setLeft(0);
 page.getParagraphs().add(image);
 doc.save(dataDir + "ImagetoPDF.pdf");
} catch (Exception e) {
 readImage = null;
 e.printStackTrace();
}

ImagetoPDF.pdf (80.1 KB)

Thanks.
Which jar file have I to import for “BufferedImage” class ?

Thanks

@vfiot

We used java.awt.image library to get height and width of the image. You can however use any library or class to load the image from file and get its dimensions.