Sunday, 12 April 2020

Add Text and Image Watermarks to Word Documents in Java


A watermark is text or an image that displays behind the text in a document. We can put text to indicate a document’s state (confidential, draft, etc.) and can also use images to declare the authority of it. Here’s how to add text and image watermarks to word documents by using Free Spire.Doc for Java.

Add Jar to Project

Step 1. Download the latest version of Free Spire.Doc for Java from here.Unzip the package, and you’ll find Spire.Doc.jar file under the lib folder.
Step 2. Create a java project in your IED and add the jar file as a dependency. Here is what it looks like in IntelliJ IDEA.


Using the code


Example 1: Add Text Watermark
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.TextWatermark;
import com.spire.doc.documents.WatermarkLayout;
import java.awt.*;

public class WordTextWatermark {
   
public static void main(String[] args) {
      
        //create a Document object
       
Document document = new Document();
       
        //load a Word document
       
document.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.docx");
      
        //create a TextWatermark object and set the content
       
TextWatermark txtWatermark = new TextWatermark();
        txtWatermark.setText(
"Draft");
        txtWatermark.setFontSize(
40);
        txtWatermark.setColor(Color.
red);
        txtWatermark.setLayout(WatermarkLayout.
Diagonal);
       
        //apply the watermark to the document
       
document.setWatermark(txtWatermark);
       
        //save the document
       
document.saveToFile("output/TextWatermark.docx", FileFormat.Docx );
    }
}
output
Example 2: Add Image Watermark
import com.spire.doc.Document;

import com.spire.doc.FileFormat;

import com.spire.doc.PictureWatermark;


public class WordImageWatermark {

    public static void main(String[] args) {



        //create a Document object

        Document document = new Document();



        //load a Word document

        document.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.docx");



        //create a PictureWatermark object and set the image path

        PictureWatermark picture = new PictureWatermark();

        picture.setPicture("C:\\Users\\Test1\\Desktop\\logo.png");

        picture.isWashout(false);

        picture.setScaling(200);



        //apply image watermark to the document

        document.setWatermark(picture);



        //save to file

        document.saveToFile("output/ImageWatermark.docx", FileFormat.Docx );

    }

}
output

No comments:

Post a Comment

Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...