@dixit44,
The problem occurs because watermark shape resides inside header footer story and main content is inside body story (please see Story class). If you insert a watermark using Microsoft Word 2019, you will observe the same behavior. All content of document’s header/footer is always behind the main content of the document.
However, you may overcome this problem by manually inserting watermarks in each Page. You can achieve this by moving the cursor to the first Run in each Page of your document and then making those Runs as an anchor points for your watermarks. Please see the following code for example:
Document doc = new Document("E:\\Temp\\Word\\UI Flow for atv-tables-crudDoc.doc");
Node[] runs = doc.getChildNodes(NodeType.RUN, true).toArray();
for (int i = 0; i < runs.length; i++) {
Run run = (Run) runs[i];
int length = run.getText().length();
Run currentNode = run;
for (int x = 1; x < length; x++) {
currentNode = SplitRun(currentNode, 1);
}
}
DocumentBuilder builder = new DocumentBuilder(doc);
PageSetup ps = builder.getPageSetup();
NodeCollection smallRuns = doc.getChildNodes(NodeType.RUN, true);
LayoutCollector collector = new LayoutCollector(doc);
int pageIndex = 1;
for (int i = 0; i < smallRuns.getCount(); i++) {
Run run = (Run) smallRuns.get(i);
if (collector.getStartPageIndex(run) == pageIndex) {
Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT);
watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE);
watermark.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE);
watermark.setWidth(300);
watermark.setHeight(70);
watermark.setHorizontalAlignment(HorizontalAlignment.CENTER);
watermark.setVerticalAlignment(VerticalAlignment.CENTER);
watermark.setRotation(-40);
watermark.getFill().setColor(Color.GRAY);
watermark.setStrokeColor(Color.GRAY);
watermark.getTextPath().setText("ALTICE CONFIDENTIAL");
watermark.getTextPath().setFontFamily("Arial");
watermark.setName("WaterMark_" + i + "");
watermark.setWrapType(WrapType.NONE);
builder.moveTo(run);
builder.insertNode(watermark);
pageIndex++;
}
}
doc.save("E:\\Temp\\Word\\awjava-20.3.doc");
private static Run SplitRun(Run run, int position) throws Exception {
Run afterRun = (Run) run.deepClone(true);
afterRun.setText(run.getText().substring(position));
run.setText(run.getText().substring(0, position));
run.getParentNode().insertAfter(afterRun, run);
return afterRun;
}
Hope, this helps.