以前はWordにウォーターマークを追加する方法を紹介しましたが、今回はWordに複数の文字のウォーターマークを追加する方法を紹介することにします。 Free Spire.Doc for Javaというライブラリを使って簡単にできますよ。
下準備
1.E-iceblueの公式サイトからFree Spire.doc for Java無料版をダウンロードしてください。
2.IDEを起動して新規プロジェクトを作成してから、インストールされたファイルにあった相応しいSpire.doc.jarを参照に追加してください。
コード
```JAVA 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) {
//ドキュメントをロードします。
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);
//テキストの位置・形式を配置します。
shape.setVerticalPosition(20);
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);
//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++) {
//テキストをコピーします。
shape = (ShapeObject) shape.deepClone();
shape.setVerticalPosition(40 + 120 * i);
shape.setHorizontalPosition(20 + 130 * j);
paragraph1.getChildObjects().add(shape);
}
}
}
//保存します。
doc.saveToFile("output/AddMultipleTextWatermark.docx", FileFormat.Docx_2013);
}
}
<h4><strong>実行結果</strong></h4>
<p><img src="https://cdn-ak.f.st-hatena.com/images/fotolife/l/lendoris/20210114/20210114145451.png" alt="f:id:lendoris:20210114145451p:plain" title="" class="hatena-fotolife" itemprop="image" /></p>
<p> </p>