Free Support Forum - aspose.com

Unable to center align image on the page using DocumentBuilder

We are unable to center align image on the page using DocumentBuilder of Aspose.Words in Java. The final document is being saved as PDF.

The code is below:

String filename = UUID.randomUUID().toString();
        
com.aspose.words.Document doc = new com.aspose.words.Document();

com.aspose.words.DocumentBuilder builder = new com.aspose.words.DocumentBuilder(doc);

//Page Setup
builder.getPageSetup().setPaperSize(com.aspose.words.PaperSize.A4);
builder.getPageSetup().setTopMargin(com.aspose.words.ConvertUtil.inchToPoint(0.5));
builder.getPageSetup().setBottomMargin(com.aspose.words.ConvertUtil.inchToPoint(0.5));
builder.getPageSetup().setLeftMargin(com.aspose.words.ConvertUtil.inchToPoint(0.5));
builder.getPageSetup().setRightMargin(com.aspose.words.ConvertUtil.inchToPoint(0.5));

//Insert Logo
com.aspose.words.Shape shape = builder.insertImage("resources/logo.png", com.aspose.words.ConvertUtil.pixelToPoint(106.5),
            		com.aspose.words.ConvertUtil.pixelToPoint(106.5));
shape.setHorizontalAlignment(com.aspose.words.HorizontalAlignment.CENTER);
shape.setRelativeHorizontalPosition(com.aspose.words.RelativeHorizontalPosition.PAGE);
shape.setLeft((builder.getPageSetup().getPageWidth() - shape.getWidth()) / 2);

doc.save("resources/"+filename+".pdf", com.aspose.words.SaveFormat.PDF);

Please suggest solution to the problem.

Thanks.

@mussab,

You need to set Wrap Type of Shape to None. Please try the following Java code:

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.getPageSetup().setPaperSize(com.aspose.words.PaperSize.A4);
builder.getPageSetup().setTopMargin(com.aspose.words.ConvertUtil.inchToPoint(0.5));
builder.getPageSetup().setBottomMargin(com.aspose.words.ConvertUtil.inchToPoint(0.5));
builder.getPageSetup().setLeftMargin(com.aspose.words.ConvertUtil.inchToPoint(0.5));
builder.getPageSetup().setRightMargin(com.aspose.words.ConvertUtil.inchToPoint(0.5));

com.aspose.words.Shape shape = builder.insertImage("C:\\Temp\\logo.png", com.aspose.words.ConvertUtil.pixelToPoint(106.5),
        com.aspose.words.ConvertUtil.pixelToPoint(106.5));
shape.setHorizontalAlignment(com.aspose.words.HorizontalAlignment.CENTER);
shape.setRelativeHorizontalPosition(com.aspose.words.RelativeHorizontalPosition.PAGE);
// shape.setLeft((builder.getPageSetup().getPageWidth() - shape.getWidth()) / 2);
shape.setWrapType(WrapType.NONE);

doc.save("C:\\temp\\awjava-20.9.pdf");

Setting Wrap Type of Shape to TOP_BOTTOM worked for us as we also had some text below the image.

Thanks a lot.

@mussab,

It is great that you were able to find what you were looking for. Please let us know any time you may have any further queries in future.