How to Set Opacity of Image Shape using Java

Hi Team,

We observe an issue while adding images as logo in the word documents.
Can you please help us to insert the image logo in a word document without adding it into the header or footer because we have added but the image gets blur?

Below code is used:

// private static void insertWatermarkImageIntoWordDocument(Document doc, String watermarkImagePath, DocumentBuilder builder) throws Exception {
Shape watermark = new Shape(doc, ShapeType.IMAGE);

watermark.getImageData().setImage(watermarkImagePath);

	
	watermark.setWidth(80);
	watermark.setHeight(35);

	// Place the watermark in the page center.
	watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE);
	watermark.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE);
	watermark.setWrapType(WrapType.NONE);
	watermark.setLeft(100);
	watermark.setTop(100);
	
	// Create a new paragraph and append the watermark to this paragraph.
	Paragraph watermarkPara = new Paragraph(doc);
	watermarkPara.appendChild(watermark);

// // Insert the watermark into all headers of each document section.
for (Section sect : doc.getSections())
{

		insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_PRIMARY);

		insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_FIRST);

		insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_EVEN);
	}
}

private static void insertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, int headerType)
throws Exception {
HeaderFooter header = sect.getHeadersFooters().getByHeaderFooterType(headerType);

	if (header == null) {

// builder.moveToHeaderFooter(HeaderFooterType.HEADER_FIRST);
// // There is no header of the specified type in the current section, create it.
header = new HeaderFooter(sect.getDocument(), headerType);
sect.getHeadersFooters().add(header);
}

	// Insert a clone of the watermark into the header.
	header.appendChild(watermarkPara.deepClone(true));
}

Thanks in advance.

@ravi.vishwakarma

Please use the latest version of Aspose.Words for Java 20.12 and read following article to insert watermark into document. Hope this helps you.

Working with Watermark

If you still face problem, please ZIP and attach your input, problematic and expected output documents. We will investigate the issue and provide you more information on it.

Hi Tahir,

I have tried with the version 20.12 but still facing issue.
Attaching the input, output and expected output files for reference.
samples.zip (169.4 KB)

You can check that color of the image gets faded.
Please help.

can you please help me to add the border is the word file?

@ravi.vishwakarma

You are inserting the watermark image into document and it is inserted in the header of document. So, it is faded. In your expected output document, the image is inserted at the start of document. You can achieve it by moving the cursor to the document’s start using DocumentBuilder.MoveToDocumentStart method and insert the image.

We suggest you please read the following articles.
Use DocumentBuilder to Insert Document Elements
Using DocumentBuilder to Modify a Document

Thanks Tahir, We have achieved it by using the method moveToDocumentStart().

Can you please suggest how I can add the same image in all the pages of document.

@ravi.vishwakarma

Please use the following code example to insert the image on each page of document. Hope this helps you.

Document doc = new Document(MyDir + "input.docx");
InsertWatermarkeAtEachPage(doc, MyDir + "input.png");

doc.save(MyDir + "20.12.docx");

public static void InsertWatermarkeAtEachPage (Document doc, String imagepath) 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(Paragraph para : (Iterable<Paragraph>)paragraphs)
        {
            if (collector.getStartPageIndex(para) == pageIndex)
            {
                builder.moveToParagraph(paragraphs.indexOf(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;

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

            Shape watermark = new Shape(doc, ShapeType.IMAGE);

            watermark.getImageData().setImage(imagepath);

            watermark.setTop(PageRelativeY);
            watermark.setLeft(PageRelativeX);

            watermark.setWidth(500);
            watermark.setHeight(100);

            para.appendChild(watermark);

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

            Boolean isInCell = bookmark.getBookmarkStart().getAncestor(NodeType.CELL) != null;
            if (isInCell)
            {
                Object renderObject = collector.getEntity(bookmark.getBookmarkStart());
                layoutEnumerator.setCurrent(renderObject);

                layoutEnumerator.moveParent(LayoutEntityType.CELL);

                watermark.setTop(PageRelativeY - layoutEnumerator.getRectangle().getY());
                watermark.setLeft(PageRelativeX - layoutEnumerator.getRectangle().getX());
            }
        }
    }
}

Thanks, Tahir Now we are able to add the images in the document.

@ravi.vishwakarma

Please feel free to ask if you have any question about Aspose.Words, we will be happy to help you.

Can you please suggest how I can set the transparency of the image?

@ravi.vishwakarma

Unfortunately, Aspose.Words does not provide API to set opacity/transparency of image shape. The issue ID for this feature is WORDSNET-19658. We will inform you via this forum thread once this feature is available. We apologize for your inconvenience.

You can use Aspose.Imaging for Java API to set the transparency of image and insert that image into Word document. Please read the following article for more detail.
Specifying Transparency for PNG Images

ok thanks for the help.

@ravi.vishwakarma

Please feel free to ask if you have any question about Aspose.Words, we will be happy to help you.

The issues you have found earlier (filed as WORDSNET-19658) have been fixed in this Aspose.Words for .NET 21.10 update also available on NuGet.