Customizing image placement

Dear Support,

I’m trying to import a TIFF image into a PDF file. I have found two tutorials here and here, but neither of them works. It seems like VerticalAlignment.Middle does not exist, and the image object does not have the setRectangle method. Were there any changes in image placement since Aspose.PDF version 21.9? I’m currently using version 24.6 with Aspose.Total license.

private void importImage() {
    try (com.aspose.pdf.Document pdfDocument = new com.aspose.pdf.Document(*path to pdf*)) {
        com.aspose.pdf.Page page = pdfDocument.getPages().get_Item(1); 
        com.aspose.pdf.Image image = new com.aspose.pdf.Image();
        image.setFile(*path to tiff*);
        
        // Code from the second tutorial
        image.setHorizontalAlignment(HorizontalAlignment.Center);
        image.setVerticalAlignment(VerticalAlignment.Middle);
        image.setRectangle(new Rectangle(100, 100, 200, 200));

        page.getParagraphs().add(image);
        pdfDocument.save(*output path*);

        System.out.println("TIFF image successfully added to the PDF.");
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Error occurred while processing!");
    }
}

I would appreciate any information regarding this issue.
Thank you in advance!

@grigonaz

The referenced links are outdated and we are not maintaining these domains. The VerticalAlignment enumeration contains Center property now instead of Middle. Also, there is no such method as setRectangle for the Image Class.

Below code can be used to add image inside PDF:

BufferedImage originalImage = ImageIO.read(new File(dataDir + "image.png"));
Document doc = new Document();
Page page = doc.getPages().add();
com.aspose.pdf.Image image = new Image();
image.setBufferedImage(originalImage);
//image.setFile(dataDir + "ActualPNG.png");
// Set margins so image will fit, etc.
page.getPageInfo().getMargin().setBottom(0);
page.getPageInfo().getMargin().setTop(0);
page.getPageInfo().getMargin().setLeft(0);
page.getPageInfo().getMargin().setRight(0);

// Get the width of the image
int width = originalImage.getWidth();
// Get the height of the image
int height = originalImage.getHeight();

page.getPageInfo().setWidth(originalImage.getWidth());
page.getPageInfo().setHeight(originalImage.getHeight());

page.getParagraphs().add(image);
doc.save(dataDir + "output.pdf");

However, if you need to control image position inside PDF, it is recommended to use ImageStamp Class:

1 Like