Wednesday, 24 February 2021

Add multiple image watermarks to Word documents in Java

I introduced how to add multiple text watermarks to a Word document in Java before. Today, this tutorial will demonstrate how to add multiple image watermarks to a Word document in Java.

Dependency

It’s worth mentioning that I used a free third-party library called Free Spire.doc for Java to achieve the effect I want. Before typing codes, you need to add the jar file in the library to IDEA. Please click the link to download the product package and manually add Spire.doc.jar to IDEA, or directly reference it using the following Maven configurations.

<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>
Using the code

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.HeaderFooter;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextWrappingStyle;
import com.spire.doc.fields.DocPicture;

public class Watermark {
public static void main(String[] args) {
//Load the sample file
Document doc=new Document();
doc.loadFromFile(
"C:\\Users\\Test1\\Desktop\\Sample.docx");
//Load the image
DocPicture picture = new DocPicture(doc);
picture.loadImage(
"C:\\Users\\Test1\\Desktop\\Image.png");

//Set the text wrapping style
picture.setTextWrappingStyle(TextWrappingStyle.Behind);

for (int n = 0; n < doc.getSections().getCount(); n++) {
Section section = doc.getSections().get(n);
//Get the head of section
HeaderFooter header = section.getHeadersFooters().getHeader();
Paragraph paragrapg1;
if(header.getParagraphs().getCount()>0){
paragrapg1=header.getParagraphs().get(
0);

}
else {
//Add the header to the paragraph
paragrapg1 = header.addParagraph();
}

for (int p = 0; p < 3; p++) {

for (int q = 0; q < 2; q++) {
//copy the image and add it to many places
picture = (DocPicture)picture.deepClone();
picture.setVerticalPosition(
100 + 200 * p);
picture.setHorizontalPosition(
50 + 210 * q);
paragrapg1.getChildObjects().add(picture);
}
}
}
//Save the document to file
doc.saveToFile("output/AddMultipleImageWatermark.docx", FileFormat.Docx_2013);
}
}

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...