DEV Community

carlwils
carlwils

Posted on

Java: Add an Image Stamp to a Word Document

Stamps can guarantee the authenticity and validity of a document and also make the document look more professional. Since Microsoft Word doesn't provide a built-in stamp feature, you can add an image to your Word documents to mimic the stamp effect. This is useful when the document will be printed to paper or PDF. In this article, you will learn how to add a "stamp" to a Word document using Free Spire.Doc for Java.

Import JAR Dependency

Method 1: Download the free API and unzip it. Then add the Spire.Doc.jar file to your Java application as dependency.
Method 2: You can also add the jar dependency to maven project by adding the following configurations to the pom.xml.

<repositories>
   <repository>
      <id>com.e-iceblue</id>
      <name>e-iceblue</name>
      <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
   </repository>
</repositories>
<dependencies>
   <dependency>
      <groupId>e-iceblue</groupId>
      <artifactId>spire.doc.free</artifactId>
      <version>3.9.0</version>
   </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Sample Code

Free Spire.Doc for Java offers the Paragraph.appendPicture() method to add an image to the Word document, and then you can use the methods offered by DocPicture class to format the image to make it look like a stamp.

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextWrappingStyle;
import com.spire.doc.fields.DocPicture;

public class AddStamp {
    public static void main(String[] args) {
        //Create a Document instance
        Document doc = new Document();

        //Load a Word document
        doc.loadFromFile("test.docx");

        //Get the specific paragraph
        Section section = doc.getSections().get(0);
        Paragraph paragraph = section.getParagraphs().get(4);

        //Add an image 
        DocPicture picture = paragraph.appendPicture("cert.png");

        //Set the position of the image
        picture.setHorizontalPosition(240f);
        picture.setVerticalPosition(120f);

        //Set width and height of the image
        picture.setWidth(150);
        picture.setHeight(150);

        //Set wrapping style of the image to In_Front_Of_Text, so that it looks like a stamp
        picture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text);

        //Save the document to file
        doc.saveToFile("AddStamp.docx", FileFormat.Docx);
        doc.dispose();
    }
}
Enter fullscreen mode Exit fullscreen mode

ImageStamp

Discussion (0)