While setting watermark image(background image),not able to set for middle pages but able to set first and last pages in .docx files

Hi, I tried converting .doc to .docx file format using Aspose library in java.

Java Version :8 (JDK : 1.8.0_351)
Aspose jar version: aspose-words-23.1.jar

While setting watermark image(background image),not able to set for middle pages but able to set first and last pages in .docx files.

// Insert the watermark shape
Shape MMGGwatermark = createWatermarkShape(doc, "watermark" + (pageIndex + 1) + ".png",

private static Shape createWatermarkShape(Document doc, String imagePath, double bckImageTop, double bckImageLeft) throws Exception {
    // Create a new shape with the watermark image
    Shape watermark = new Shape(doc, ShapeType.IMAGE);
    watermark.getImageData().setImage("D:\\JavaApplication1\\src\\" + imagePath);

    // Set the width and height of the watermark image independently
    watermark.setWidth(558.0);
    watermark.setTop(bckImageTop);
    watermark.setLeft(bckImageLeft);
    //watermark.setHeight(100);

    // Position the watermark image
    watermark.setWrapType(WrapType.NONE);
    watermark.setBehindText(true);
    watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE);
    watermark.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE);
    //watermark.setHorizontalAlignment(HorizontalAlignment.CENTER);
    //watermark.setVerticalAlignment(VerticalAlignment.CENTER);

    return watermark;
}

Also tried using bookmarks to set background image.
But its always points to first page.

// using bookmark
InsertWatermarkImageAtEachPage(doc, "watermark1.png");
	
	
public static void InsertWatermarkImageAtEachPage (Document doc, String watermarkImagePath) throws Exception
{
    DocumentBuilder builder = new DocumentBuilder(doc);

    LayoutCollector collector = new LayoutCollector(doc);

    int pageIndex = 1;
    for (Section section : doc.getSections())
    {
        NodeCollection paragraphs = section.getBody().getChildNodes(NodeType.PARAGRAPH, true);
        for (Iterator it = paragraphs.iterator(); it.hasNext();) {
            Paragraph para = (Paragraph)it.next();
            if (collector.getStartPageIndex(para) == pageIndex)
            {
                builder.moveToParagraph(collector.getStartPageIndex(para), 0);
                builder.startBookmark("BM_Page" + pageIndex);
                builder.endBookmark("BM_Page" + pageIndex);
                pageIndex++;
                
            }
        }
    }

    collector = new LayoutCollector(doc);
    LayoutEnumerator layoutEnumerator = new LayoutEnumerator(doc);

    int PageRelativeY = 50;
    int PageRelativeX = 50;
    int pageind=0;
Paragraph para;

    for (Bookmark bookmark : doc.getRange().getBookmarks())
    {
        if (bookmark.getName().startsWith("BM_"))
        {
             para = (Paragraph)bookmark.getBookmarkStart().getParentNode();
            DocumentBuilder builder1 = new DocumentBuilder(doc);

            Shape watermark = new Shape(doc, ShapeType.IMAGE);
            builder1.moveToBookmark(bookmark.getName(),true,true);
            
            if(bookmark.getName().equals("BM_Page2")){
                builder1.moveToBookmark("BM_Page2");
                watermark.setTop(70.0);
                watermark.setLeft(24.0);
              watermark.getImageData().setImage("D:\\JavaApplication1\\src\\watermark2.png");
              
            }
            else {
                builder1.moveToBookmark("BM_Page1");
                watermark.setTop(0.0);
                watermark.setLeft(0.0);
              watermark.getImageData().setImage("D:\\JavaApplication1\\src\\watermark1.png");
              
            }
            //Set the width height according to your requirements
            watermark.setWidth(558.0);
           // watermark.setHeight(625);
            watermark.setBehindText(true);

            builder1.insertNode(watermark);

            watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE);
            watermark.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE);

            Boolean isInCell = bookmark.getBookmarkStart().getAncestor(NodeType.CELL) != null;        
        }
        pageind++;
    }
}

@jebinym please note that there are two approaches you can take when adding a watermark to a document:

  1. Using the Watermark class: This approach replicates how MS Word adds a watermark. You can refer to the example provided here for guidance on implementing this method.
  2. Inserting a shape on each page: It seems that you are currently using this approach. To achieve your expected output, you can refer to the following code snippet:
Document doc = new Document("C:\\Temp\\input.docx");
LayoutCollector collector = new LayoutCollector(doc);
int pageIndex = 1;
for (com.aspose.words.Section section : doc.getSections())
{
    PageSetup pageSetup = section.getPageSetup();

    double contentWidth = pageSetup.getPageWidth() - (pageSetup.getLeftMargin() + pageSetup.getRightMargin());
    double contentHeight = pageSetup.getPageHeight() - (pageSetup.getTopMargin() + pageSetup.getBottomMargin());

    var paragraphs = section.getBody().getChildNodes(NodeType.PARAGRAPH, true);
    for (var item : paragraphs)
    {
        var para = (Paragraph)item;
        if (collector.getStartPageIndex(para) == pageIndex)
        {
            Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT);
            watermark.getTextPath().setText("TEST WATERMARK IN WORD");
            watermark.getTextPath().setFontFamily("Arial");
            // Set the width height according to your requirements
            watermark.setWidth(175);
            watermark.setBehindText(false);
            watermark.setRotation(-40);
            watermark.setHeight(20);
            watermark.setFillColor(Color.RED);
            watermark.setStrokeColor(Color.RED);
            watermark.setZOrder(2);

            watermark.setLeft((contentWidth - watermark.getWidth()) / 2);
            watermark.setHorizontalAlignment(HorizontalAlignment.NONE);
            watermark.setTop((contentHeight - watermark.getHeight()) / 2);
            watermark.setVerticalAlignment(VerticalAlignment.NONE);

            para.appendChild(watermark);
            pageIndex++;
        }
    }
}

doc.save("C:\\Temp\\output.docx");

By following either of these approaches, you can successfully add a watermark to your document.

Thanks for your response but Still have the following issues

Tried with different background images for each page using the page index.

Some pages have the background as expected.

Some pages showing some other background image which is set to another page.

Some pages not showing the background image.

Also, some pages shows two background images.

Total pages wrong, actually 17 pages but it shows wrongly 23 pages.

@jebinym Could you please provide the input and current output document files for further analysis? It would greatly help in understanding and addressing the issue.

We are able to set the background image for the specific pages using the section.
Not able to add images in the footer.

String htmlFooter = "<img src=''>";
DocumentBuilder builder = new DocumentBuilder(doc);
builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
builder.insertHtml(htmlFooter)

Also tried the below approach but throws an error as “Cannot insert a node of this type at this location.”

com.aspose.words.HeaderFooter footer = section.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY);
          
// Create a shape object for the image
Shape imageShape = new Shape(doc, ShapeType.IMAGE);

// Set the image file path
String imagePath = "D:\\1.png";
imageShape.getImageData().setImage(imagePath);

// Set the size and position of the image shape

imageShape.setWidth(100);
imageShape.setHeight(100);
imageShape.setLeft(0);
imageShape.setTop(0);

// Add the shape to the footer
footer.appendChild(imageShape);

@jebinym The image is properly inserted from HTML. I have used the following code for testing:

String htmlFooter = "<img src='https://cms.admin.containerize.com/templates/aspose/App_Themes/V3/images/aspose-logo.png'>";
        
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
builder.insertHtml(htmlFooter);
doc.save("C:\\Temp\\out.docx");

Regarding the second code snippet, Shape is an inline node and cannot be a direct child of Header/Footer note, it can be child of a paragraph or group shape. So you should modify your code like this:

// Add the shape to the last paragraph of the footer
footer.getLastParagraph().appendChild(imageShape);

Please see our documentation to learn more about Aspose.Words Document Object Model.