Word中设置水印效果时,不论是文本水印或者是图片水印都只能添加单个文字或者图片到Word页面,效果比较单一,本文通过Java代码示例介绍如何在页面中添加多行水印效果,即水印效果以多行文字排列或者以多个图片平铺到页面。
思路及方法:获取Word页眉,添加形状(在形状中添加文字)或者图片到页眉段落,并复制形状或图片。
程序环境:使用spire.doc.jar,版本:免费版3.9.0
?
1. 添加多行文字水印效果
class="java">import com.spire.doc.*; 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 TextWatermark { 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().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); //获取页眉 header = section.getHeadersFooters().getHeader(); Paragraph paragraph1; for (int i = 0; i < 4; i++) { //添加4个段落到页眉 paragraph1 = header.addParagraph(); for (int j = 0; j < 3; j++) { //复制艺术字并设置多行多列位置 shape = (ShapeObject) shape.deepClone(); shape.setVerticalPosition(50 + 200 * i); shape.setHorizontalPosition(20 + 160 * j); paragraph1.getChildObjects().add(shape); } } } //保存文档 doc.saveToFile("result.docx", FileFormat.Docx_2013); doc.dispose(); } }
?
2. 添加多行图片水印
import com.spire.doc.*; import com.spire.doc.documents.Paragraph; import com.spire.doc.documents.TextWrappingStyle; import com.spire.doc.fields.DocPicture; public class ImageWatermark { public static void main(String[] args) { //加载Word文档 Document doc=new Document(); doc.loadFromFile("input.docx"); //加载图片 DocPicture picture = new DocPicture(doc); picture.loadImage("logo.png"); picture.setTextWrappingStyle(TextWrappingStyle.Behind);//设置图片环绕方式 //遍历所有section 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 < 4; p++) { for (int q = 0; q < 3; q++) { picture = (DocPicture)picture.deepClone(); picture.setVerticalPosition(50 + 150 * p); picture.setHorizontalPosition(10 + 140 * q); paragrapg1.getChildObjects().add(picture); } } } //保存文档 doc.saveToFile("output.docx", FileFormat.Docx_2013); doc.dispose(); } }
?
?
?