Skip to main content

How to Add Watermarks to Word Documents with Java: A Comprehensive Guide

 

Introduction

In modern enterprise office environments, document security and copyright protection are crucial. Whether it’s a confidential internal document or a draft sample shared externally, watermarks are the most intuitive and cost-effective way to safeguard content.

For Java developers, working with Word documents (.doc / .docx) can often be tricky. While Apache POI offers low-level support, its complex API can make simple formatting adjustments unnecessarily difficult. Today, we will explore how to use the Spire.Doc for Java library to implement professional-grade watermarking with just a few lines of code.

1. Why Choose Spire.Doc for Java?

There are many tools in the Java ecosystem for working with Word documents, but Spire.Doc stands out for several reasons:

  • Independence : No need to install Microsoft Word on the server.
  • High fidelity : Watermarks remain correctly positioned when converting to PDF or printing.
  • Intuitive API : Complex watermark objects (VML shapes) are wrapped into simple property settings.
  • Comprehensive features : Supports tiled text, image transparency adjustment, and independent settings for multiple sections.

2. Setup

First, add the necessary dependency to your pom.xml:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>14.3.1</version>
    </dependency>
</dependencies>

3. Implementation: How to Add Watermarks to Word in Java

3.1 Adding a Text Watermark

Text watermarks are the most common requirement. Spire.Doc allows you to customize font, color, rotation, and tiling.

import com.spire.doc.*;
import com.spire.doc.documents.WatermarkLayout;
import java.awt.*;

public class TextWatermark {
    public static void main(String[] args) {
        Document document = new Document();
        document.loadFromFile("input.docx");

        TextWatermark txtWatermark = new TextWatermark();
        txtWatermark.setText("Confidential - Do Not Share");
        txtWatermark.setFontSize(45);
        txtWatermark.setColor(new Color(255, 0, 0, 100)); // semi-transparent red
        txtWatermark.setLayout(WatermarkLayout.Diagonal); 

        document.setWatermark(txtWatermark);
        document.saveToFile("TextWatermark.docx", FileFormat.Docx_2013);
    }
}

3.2 Adding an Image Watermark

Image watermarks are commonly used for company logos. Key points include scaling and washout effects to make the image look like a subtle background.

import com.spire.doc.*;

public class ImageWatermark {
    public static void main(String[] args) {
        Document document = new Document();
        document.loadFromFile("input.docx");

        PictureWatermark picture = new PictureWatermark();
        picture.setPicture("logo.png");
        picture.setScaling(120);
        picture.isWashout(true); // apply washout effect

        document.setWatermark(picture);
        document.saveToFile("ImageWatermark.docx", FileFormat.Docx_2013);
    }
}

4. Advanced Tip: Dynamic Full-Page Tiled Watermarks

By default, Word watermarks are displayed only in the center of the page. To prevent screenshots or leaks, you may need a full-page tiled watermark. Since Word has limited native support for tiled text, the best approach is to insert multiple text shapes into the header . Using the deepClone() method, you can efficiently reuse a shape template across the page.

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.ShapeObject;
import java.awt.*;

public class WordWatermark {
    public static void main(String[] args) {
        Document doc = new Document();
        doc.loadFromFile("Sample.docx");

        // Create a master watermark shape
        ShapeObject shape = new ShapeObject(doc, ShapeType.Text_Plain_Text);
        shape.setWidth(60);
        shape.setHeight(20);
        shape.setRotation(315);
        shape.getWordArt().setFontFamily("SimSun");
        shape.getWordArt().setText("Internal Use");
        shape.setFillColor(new Color(192, 192, 192, 150)); // semi-transparent gray
        shape.setLineStyle(ShapeLineStyle.Single);
        shape.setStrokeWeight(1);

        // Iterate over all sections
        for (int n = 0; n < doc.getSections().getCount(); n++) {
            Section section = doc.getSections().get(n);
            HeaderFooter header = section.getHeadersFooters().getHeader();
            Paragraph paragraph = header.getParagraphs().getCount() > 0 
                                  ? header.getParagraphs().get(0) 
                                  : header.addParagraph();

            // Nested loops for tiled rows and columns
            for (int i = 0; i < 4; i++) {
                for (int j = 0; j < 3; j++) {
                    ShapeObject clonedShape = (ShapeObject) shape.deepClone();
                    clonedShape.setVerticalPosition(50 + 150 * i);
                    clonedShape.setHorizontalPosition(20 + 160 * j);
                    paragraph.getChildObjects().add(clonedShape);
                }
            }
        }
        doc.saveToFile("result.docx", FileFormat.Docx_2013);
    }
}

5. FAQ

  • Why does my watermark disappear when converting to PDF?

This is usually due to incorrect layering. Using document.setWatermark() is the most reliable method. If manually adding shapes, make sure to set VerticalOrigin.Page.

  • How can I apply a watermark to specific pages only?

Watermarks in Word are section-based. Use document.getSections().get(index) to access a specific section and apply watermarks only there.

  • Performance optimization tips

For long documents, use the deepClone() approach from section 4 to avoid creating new objects repeatedly, which can significantly save memory.


6. Enterprise Use Cases

In production, watermarks can be dynamically generated based on backend business logic:

  • Dynamic user information : Fetch the logged-in user’s name from the session.
  • Content construction : Concatenate "User: " + empName + " | " + LocalDate.now().
  • Streamed processing : Use document.saveToStream() to push watermarked documents directly to the frontend for secure downloads.

Conclusion

Adding watermarks to Word documents with Java is no longer a complicated task. With Spire.Doc , developers can focus on business logic rather than the underlying VML/XML structures, implementing secure, professional, and dynamic watermarks efficiently.

Comments

Popular posts from this blog

3 Ways to Generate Word Documents from Templates in Java

A template is a document with pre-applied formatting like styles, tabs, line spacing and so on. You can quickly generate a batch of documents with the same structure based on the template. In this article, I am going to show you the different ways to generate Word documents from templates programmatically in Java using Free Spire.Doc for Java library. Prerequisite First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file. <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>...

Insert and Extract OLE objects in Word in Java

You can use OLE (Object Linking and Embedding) to include content from other programs, such as another Word document, an Excel or PowerPoint document to an existing Word document. This article demonstrates how to insert and extract embedded OLE objects in a Word document in Java by using Free Spire.Doc for Java API.   Add dependencies First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file.     <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>    ...

Simple Java Code to Convert Excel to PDF in Java

This article demonstrates a simple solution to convert an Excel file to PDF in Java by using free Excel API – Free Spire.XLS for Java . The following examples illustrate two possibilities to convert Excel to PDF:      Convert the whole Excel file to PDF     Convert a particular Excel Worksheet to PDF Before start with coding, you need to Download Free Spire.XLS for Java package , unzip it and import Spire.Xls.jar file from the lib folder in your project as a denpendency. 1. Convert the whole Excel file to PDF Spire.XLS for Java provides saveToFile method in Workbook class that enables us to easily save a whole Excel file to PDF. import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ExcelToPDF {     public static void main(String[] args){         //Create a Workbook         Workbook workbook = new Workbook();   ...