前面我们介绍了如何使用 Spire.Doc for Java 添加多行文本水印到 Word 文档。该文将详细介绍在Word页眉中添加多行图片水印的效果。
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 WordImageWatermark {
public static void main(String[] args) throws Exception {
//加载示例文档
Document doc=new Document();
doc.loadFromFile("Sample.docx");
//加载图片
DocPicture picture = new DocPicture(doc);
picture.loadImage("Logo.png");
//设置图片环绕方式
picture.setTextWrappingStyle(TextWrappingStyle.Behind);
for (int n = 0; n < doc.getSections().getCount(); n++) {
Section section = doc.getSections().get(n);
//获取section的页眉
HeaderFooter header = section.getHeadersFooters().getHeader();
Paragraph paragrapg1;
if(header.getParagraphs().getCount()>0){
paragrapg1=header.getParagraphs().get(0);
}else {
//添加段落到页眉
paragrapg1 = header.addParagraph();
}
for (int p = 0; p < 3; p++) {
for (int q = 0; q < 2; q++) {
//复制图片并设置多行多列位置
picture = (DocPicture)picture.deepClone();
picture.setVerticalPosition(100 + 200 * p);
picture.setHorizontalPosition(50 + 210 * q);
paragrapg1.getChildObjects().add(picture);
}
}
}
//保存文档
doc.saveToFile("多行图片水印.docx", FileFormat.Docx_2013);
}
}
效果图: