给word添加水印

如何将水印添加到文档内容的上面

@jillian 在这种情况下,您可以使用 “形状”:

Document doc = new Document(getMyDir() + "Big document.docx");

// Determine the maximum ZOrder of shapes in the document.
int zOrder = 0;
Iterable<Shape> shapes = doc.getChildNodes(NodeType.SHAPE, true);
for (Shape s : shapes)
{
    zOrder = Math.max(zOrder, s.getZOrder());
}
zOrder++;

// Create a watermark shape.
Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT);
watermark.setName("WaterMark");
// Set up the text of the watermark.
watermark.getTextPath().setText("In Front Watermark");
watermark.getTextPath().setBold(true);
watermark.getTextPath().setSize(100);
watermark.getTextPath().setFontFamily("Arial");
watermark.setWidth(500);
watermark.setHeight(100);
watermark.getFill().setForeColor(Color.lightGray);
watermark.setStrokeColor(Color.lightGray);
// Text will be directed from the bottom-left to the top-right corner.
watermark.setRotation(45);
// Place the watermark in the page center.
watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE);
watermark.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE);
watermark.setWrapType(WrapType.NONE);
watermark.setHorizontalAlignment(HorizontalAlignment.CENTER);
watermark.setVerticalAlignment(VerticalAlignment.CENTER);
watermark.setZOrder(zOrder);

// Get paragraphs in the document.
Iterable<Paragraph> paragraphs = doc.getChildNodes(NodeType.PARAGRAPH, true);

LayoutCollector layoutCollector = new LayoutCollector(doc);
int pageToInsert = 1;
for (Paragraph para : paragraphs)
{
    // Process only paragraphs in the main body.
    if (para.getAncestor(NodeType.BODY) == null)
        continue;

    int paraPage = layoutCollector.getEndPageIndex(para);
    if (paraPage == pageToInsert)
    {
        pageToInsert++;
        para.appendChild(watermark.deepClone(true));
    }
}

doc.save(getArtifactsDir() + "output.docx");

// Since we have used LayoutCollector, Aspose.Words cached layout of the document
// and the modifications we have made are not in the cache.
// Update page layout to reflect the changes in the output fixed Page formats.
doc.updatePageLayout();
doc.save(getArtifactsDir() + "output.pdf");