I introduced how to add textwatermark and image watermark to a Word document before. Today, this tutorial will demonstrate how to insert multiple text watermarks to a Word document in Java programmatically. It’s worth mentioning that I used a free API called Free Spire.Doc for Java to do it.
Before running codes, an important thing you need to do is importing Spire.Doc.jar to IDEA. You can directly down the package and manually import it or use the following Maven configurations to reference it.
<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
Free Spire.Doc for Java supports inserting multiple text watermarks to a Word document by adding
WordArt shape to the Word header. Here are specific steps to do it.
Step 1: Load a Word sample and add WordArt shape.
Step 2: Set the size, text, position and style of the WordArt.
Step 3: Get the header of section and add it to the paragraph.
Step 4: Copy the text and add it to many places.
Step 5: Save the resulting file to the specified path.
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.ShapeLineStyle;
import com.spire.doc.documents.ShapeType;
import com.spire.doc.fields.ShapeObject;
import java.awt.*;
public class Watermark {
public static void main(String[] args) {
//Load the sample document
Document doc = new Document();
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.docx");
//Add WordArt shape and set the size
ShapeObject shape = new ShapeObject(doc, ShapeType.Text_Plain_Text);
shape.setWidth(50);
shape.setHeight(15);
//Set the text, position and style for the WordArt
shape.setVerticalPosition(20);
shape.setHorizontalPosition(20);
shape.setRotation(315);
shape.getWordArt().setText("Draft");
shape.setFillColor(Color.red);
shape.setLineStyle(ShapeLineStyle.Single);
shape.setStrokeColor(new Color(192, 192, 192, 255));
shape.setStrokeWeight(1);
Section section;
HeaderFooter header;
for (int n = 0; n < doc.getSections().getCount(); n++) {
section = doc.getSections().get(n);
//Get the header of section
header = section.getHeadersFooters().getHeader();
Paragraph paragraph1;
for (int i = 0; i < 4; i++) {
//Add the header to the paragraph
paragraph1 = header.addParagraph();
for (int j = 0; j < 3; j++) {
//copy the word are and add it to many places
shape = (ShapeObject) shape.deepClone();
shape.setVerticalPosition(40 + 120 * i);
shape.setHorizontalPosition(20 + 130 * j);
paragraph1.getChildObjects().add(shape);
}
}
}
//Save the document to file
doc.saveToFile("output/AddMultipleTextWatermark.docx", FileFormat.Docx_2013);
}
}Output
No comments:
Post a Comment