前面我们介绍了如何使用 Spire.Doc for Java 添加文本水印和图片水印到 Word 文档。该文将详细介绍在Word页眉中添加艺术字实现Word文档中多行文字水印效果。
添加多行文本水印:
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");
//添加艺术字并设置大小
ShapeObject shape = new ShapeObject(doc, ShapeType.Text_Plain_Text);
shape.setWidth(60);
shape.setHeight(20);
//设置艺术字文本内容、位置及样式
shape.setVerticalPosition(30);
shape.setHorizontalPosition(20);
shape.setRotation(315);
shape.getWordArt().setFontFamily("宋体");
shape.getWordArt().setText("内部使用");
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);
//获取section的页眉
header = section.getHeadersFooters().getHeader();
Paragraph paragraph;
if (header.getParagraphs().getCount() > 0) {
//如果页眉有段落,取它第一个段落
paragraph = header.getParagraphs().get(0);
} else {
//否则新增加一个段落到页眉
paragraph = header.addParagraph();
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 3; j++) {
//复制艺术字并设置多行多列位置
shape = (ShapeObject) shape.deepClone();
shape.setVerticalPosition(50 + 150 * i);
shape.setHorizontalPosition(20 + 160 * j);
paragraph.getChildObjects().add(shape);
}
}
}
//保存文档
doc.saveToFile("result.docx", FileFormat.Docx_2013);
}
}
效果图: