Auto-fit image in pdf without losing the ratio

Hi team,

I’m trying to convert Annotation 2022-11-23 111626.png (8.3 KB)
to a pdf using the following code -

public byte[] convertImageToPdf(ByteArrayInputStream input, String extension) throws Exception {
    log.info("Initiating image to pdf conversion");
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    try {
        // Initialize document object
        com.aspose.pdf.Document document = new com.aspose.pdf.Document();

        // Set local font location
        FontRepository.setLocalFontPaths(ImmutableList.of(fontsPath));
        Page page = document.getPages().add();
        Image image = new Image();

        // Load sample JPEG image file
        image.setImageStream(input);
        page.getParagraphs().add(image);

        // Save output PDF document
        document.save(result);
        return result.toByteArray();
    } catch (Exception ex) {
        log.error("Exception occurred while converting Image to pdf :", ex);
        throw ex;
    } finally {
        result.close();
    }
}

We are getting the image that’s shrunk to fit the page.
We want the image to retain the aspect-ratio and auto-fit inside the page.

Please help

Thanks,
Shaurya

@shaurya.chawla

Please try to use the below code snippet in order to get desired output:

BufferedImage readImage = null;

        try {
            readImage = ImageIO.read(new File(dataDir + "Annotation 2022-11-23 111626.png"));
            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 + "Annotation 2022-11-23 111626.png");
            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 (53.8 KB)

That worked perfectly. Thanks for your help!