Images like bmp or jpeg conversion to PDF lost aspect ratio and quality

I converted some image files to PDF using the following code. I expected image’s aspect ration will be maintained, but it somehow did not do it.

The image quality in PDF document seems to have smaller resolution comparing to the original document. Is there any way to maintain the image quality? I am adding the image sample and PDF sample here.

I am not sure whether my code is wrong or this is something to happen all the time with PDF conversion.

Thanks/Kevin

Document doc = new Document();

        Page page = doc.getPages().add();

        FileInputStream fs = new FileInputStream(data.getCachedFileName());

        BmpImage img = new BmpImage(fs);

        page.getPageInfo().getMargin().setBottom(0);

        page.getPageInfo().getMargin().setTop(0);

        page.getPageInfo().getMargin().setLeft(0);

        page.getPageInfo().getMargin().setRight(0);

        int maxWidth = img.getWidth();

        int maxHeight = img.getHeight();

        int defaultDPI = 200;

        double scaledWidth = maxWidth * defaultDPI / 300;

        double scaledHeight = maxHeight * defaultDPI / 300;

        

        log.info("maxWidth: " + maxWidth);

        log.info("maxHeight: " + maxHeight);

        log.info("scaledWidth: " + scaledWidth);

        log.info("scaledHeight: " + scaledHeight);

        page.setCropBox(new Rectangle(0, 0, scaledWidth, scaledHeight));

        Image image1 = new Image();

        page.getParagraphs().add(image1);

        FileInputStream fsInput = new FileInputStream(data.getCachedFileName());

        image1.setImageStream(fsInput);

        doc.save(outputPdfLocation());

        img.close();<a class="attachment" href="/uploads/default/44718">129846442.pdf</a> (550.8 KB)

EB007.zip (1.2 MB)

Thank you for your help.

Kevin

@kshengivari

Attached output PDF has been generated using following code snippet in our environment. Would you please check it and let us know what type of issues your observe in it:

BufferedImage readImage = null;

try {
 readImage = ImageIO.read(new File(dataDir + "129846442.bmp"));
 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 + "129846442.bmp");
 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;
}

ImagetoPDF.pdf (550.8 KB)

thank you that fixes it.

1 Like