How to add watermark text in cover page of word document

Hi
How to add a watermark to the cover page of a word document using Aspose Words API for Java.

Now watermark text appears in all other pages and not in cover page.

Following code is being used now

boolean watermarkedFile = false;

String fileName = "";
try
{

    fileName = wordFile.getName();
    String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);
    String filePath = wordFile.getPath();
    String fileExtension = ".docx";
    if (!fileName.endsWith(".docx"))
    {
        fileExtension = ".doc";
    }

    //to apply license 
    //  com.aspose.words.License license = new com.aspose.words.License();
    //  license.setLicense("Aspose.Total.Java.lic");

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

    //	com.aspose.words.Watermark watermark = new Watermark(watermarkText);

    // Create a shape to hold the watermark text
    //   Shape watermarkShape = watermark.createWatermarkShape(doc);

    com.aspose.words.Shape watermark = new com.aspose.words.Shape(doc, com.aspose.words.ShapeType.TEXT_PLAIN_TEXT);
    watermark.getTextPath().setText(watermarkText);
    //    watermark.getTextPath().setFontFamily("Arial");
    //    watermark.setWidth(300.0);
    watermark.setWidth(500.0);
    watermark.setHeight(15.0);
    //	    watermark.setRelativeHorizontalPosition(com.aspose.words.RelativeHorizontalPosition.PAGE);
    //	    watermark.setRelativeVerticalPosition(com.aspose.words.RelativeVerticalPosition.PAGE);
    //    watermark.setWrapType(com.aspose.words.WrapType.NONE);
    //    watermark.setVerticalAlignment(com.aspose.words.VerticalAlignment.CENTER);
    //    watermark.setHorizontalAlignment(com.aspose.words.HorizontalAlignment.CENTER);
    watermark.getTextPath().setFontFamily("Courier");
    //   watermark.getTextPath().setSize(15);
    watermark.getTextPath().setSize(8);
    watermark.getTextPath().setBold(false);
    //   watermark.getTextPath().setFitShape(true);
    //    watermark.setRotation(40); // Adjust the angle
    //  watermark.getFill().setColor(new Color(192, 192, 192)); // Adjust the color
    //     watermark.getFill().setColor(Color.RED); // Adjust the color
    // watermark.setFillColor(Color.RED);
    watermark.setStrokeColor(Color.RED);
    watermark.getFill().setTransparency(0); // Adjust the transparency
                                            //    builder.moveToHeaderFooter(com.aspose.words.HeaderFooterType.FOOTER_FIRST);
                                            //     builder.write(watermarkText);
    for (Section section : doc.getSections())
    {
        //	section.get
        Paragraph watermarkPara = new Paragraph(doc);
        watermarkPara.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
        watermarkPara.appendChild(watermark.deepClone(true));
        //	HeaderFooter header = section.getHeadersFooters().getByHeaderFooterType(com.aspose.words.HeaderFooterType.HEADER_PRIMARY);
        //	HeaderFooter hfooter = section.getHeadersFooters().getByHeaderFooterType(com.aspose.words.HeaderFooterType.FOOTER_FIRST);

        HeaderFooter footer = section.getHeadersFooters().getByHeaderFooterType(com.aspose.words.HeaderFooterType.FOOTER_PRIMARY);


        //	if(header != null) {
        //		header.appendChild(watermarkPara);
        //	}
        // 	if(hfooter != null) {
        // 		hfooter.appendChild(watermarkPara);
        // 	}
        if (footer != null)
        {
            footer.appendChild(watermarkPara);
        }

        //	for (Paragraph paragraph : section.getBody().getParagraphs() ) {
        //		paragraph.appendChild(watermark.deepClone(true));
        //	}
        //     for (int i = 0; i < section.getBody().getCount(); i++) {
        //         section.getBody().getParagraphs().add(watermark.deepClone(true));
        //     }
    }

    String watermarkedFilePath = outputDirectory + fileSeparator + fileNameWithOutExt + fileSuffix + fileExtension;

    doc.save(watermarkedFilePath);

    //	logger.debug("watermarkedFilePath: " + watermarkedFilePath);
    infolog.info("watermarkedFilePath: " + watermarkedFilePath);

    watermarkedFile = true;

@sabkan MS Word documents are flow by their nature, so there is no “page” concept. Consumer applications reflows document content into pages on the fly. Watermarks in MS Word document are added as a shape in the document header behind the main content. Since headers/footers are defined per section, to have a watermark only on the first page, the first page must be a separate section. You can achieve this by splitting the document into parts and then rejoining them. For example see the following code that adds a watermark only to the first page:

Document doc = new Document("C:\\Temp\\in.docx");

// Get the first page and remaining pages as separate documents.
Document firstPage = doc.extractPages(0, 1);
Document remainingPages = doc.extractPages(1, doc.getPageCount() - 1);

// Add watermark to the first page.
firstPage.getWatermark().setText("I am a cool watermark");

// make sure the remaining pages will not inherit headers/footers from the first page.
remainingPages.getFirstSection().getHeadersFooters().linkToPrevious(false);

// Rejoin the documents.
firstPage.appendDocument(remainingPages, ImportFormatMode.USE_DESTINATION_STYLES);

firstPage.save("C:\\Temp\\out.docx");

Hi

Thanks for the reply.Wanted watermark in all pages including the cover page.

@sabkan You can use the following code to add watermark to all pages of the document:

Document doc = new Document("C:\\Temp\\in.docx");
doc .getWatermark().setText("I am a cool watermark");
doc .save("C:\\Temp\\out.docx");

ok thanks.Wanted to display this watermark in the footer of each page and also in red colour.Any suggestions for the same?

@sabkan You can use watermark options to specify color of the watermark. Also, you can get the inserted watermark shapes and change their properties. Please see the following code:

Document doc = new Document("C:\\Temp\\in.docx");
TextWatermarkOptions opt = new TextWatermarkOptions();
opt.setColor(Color.red);
opt.setLayout(WatermarkLayout.HORIZONTAL);
doc.getWatermark().setText("I am a cool watermark", opt);

// Get watermark shapes and move them down.
for (Shape s : (Iterable<Shape>)doc.getChildNodes(NodeType.SHAPE, true))
{
    if (s.getName().startsWith("PowerPlusWaterMarkObject") || s.getName().startsWith("WordPictureWatermark"))
        s.setVerticalAlignment(VerticalAlignment.BOTTOM);
}

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

@alexey.noskov
Thanks.it says setVerticalAlignment method is not there .
Also Shape belongs to com.aspose.cells package, is that fine?

@sabkan

You should use com.aspose.words.Shape not com.aspose.cells.Shape. Aspose.Words and Aspose.Cells are different packages, though they have some classes with the same names. So if you are using both packages, you should use fully qualified names of classes.

@alexey.noskov
Thanks for the clarification.

1 Like