|
---------------------------------Aspose技术交流群(761297826)----------------------------—
为防止非法使用、定义所有权、显示文档状态等多种目的,在 Word 文档中添加水印。在本文中,您将学习如何使用 Java 为 Word 文档添加水印。文章将分别演示如何将文字和图片水印插入到Word文档中。
- 给 Word 文档添加文字水印
- 为 Word 文档添加图像水印
为了处理 Word 文档中的目录,我们将使用Aspose.Words for Java,它是一个强大的文字处理 API,可让您创建、修改或转换 Word 文档。
在 Java 中为 Word 文档添加文本水印
以下是使用 Java 在 Word 文档中插入文本水印的步骤。
- 首先,使用Document类加载 Word 文档。
- 创建TextWatermarkOptions类的实例来设置水印选项,例如字体系列、字体大小、颜色、布局等。
- 使用Document.getWatermark().setText(String, TextWatermarkOptions)方法向文档添加文本水印。
- 最后,使用Document.save(String)方法保存更新后的 Word 文档。
下面的代码示例展示了如何向 Word 文档添加文本水印。
// Load the Word document
Document doc = new Document("Word.docx");
// Set watermark options
TextWatermarkOptions watermarkOptions = new TextWatermarkOptions();
watermarkOptions.setFontSize(36);
watermarkOptions.setFontFamily("Arial");
watermarkOptions.setColor(Color.RED);
watermarkOptions.setLayout(WatermarkLayout.DIAGONAL);
watermarkOptions.isSemitrasparent(true);
// Insert watermark
doc.getWatermark().setText("CONFIDENTIAL", watermarkOptions);
// Save the updated document
doc.save("text-watermark.docx");以下是添加文字水印后的Word文档截图。

为 Word 文档添加图像水印
以下是使用 Java 为 Word 文档添加图像水印的步骤。
- 首先,使用Document类加载 Word 文档。
- 创建ImageWatermarkOptions类的实例以设置水印选项。
- 将水印图像加载到BufferedImage对象中。
- 使用Document.getWatermark().setImage(BufferedImage, ImageWatermarkOptions)方法为文档添加图像水印。
- 最后,使用Document.save(String)方法保存更新后的 Word 文档。
下面的代码示例展示了如何向 Word 文档添加图像水印。
// Load the Word document
Document doc = new Document("Word.docx");
// Set watermark options
ImageWatermarkOptions watermarkOptions = new ImageWatermarkOptions();
watermarkOptions.isWashout(false);
// Load watermark image
BufferedImage image = ImageIO.read(new File("logo.png"));
// Insert watermark
doc.getWatermark().setImage(image, watermarkOptions);
// Save the updated document
doc.save("image-watermark.docx");以下是添加图片水印后的Word文档截图。
 |
|