java使用 poi 版本 3.10-FINAL 给word 加多个水印 代码
时间: 2024-04-29 13:24:28 浏览: 131
poi-3.10-FINAL.jar
以下是使用poi版本3.10-FINAL给word加多个水印的示例代码:
```
import java.io.*;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.util.IOUtils;
public class AddMultipleWatermarksToWord {
public static void main(String[] args) {
try {
// Open the Word document
FileInputStream fis = new FileInputStream("input.docx");
XWPFDocument document = new XWPFDocument(fis);
// Add the first watermark
XWPFParagraph waterMark1 = document.createParagraph();
waterMark1.setAlignment(ParagraphAlignment.CENTER);
waterMark1.setVerticalAlignment(TextAlignment.CENTER);
// Add the watermark image
InputStream image1 = new FileInputStream("watermark1.png");
byte[] bytes1 = IOUtils.toByteArray(image1);
XWPFRun run1 = waterMark1.createRun();
run1.addPicture(new ByteArrayInputStream(bytes1), XWPFDocument.PICTURE_TYPE_PNG, "watermark1.png", Units.toEMU(200), Units.toEMU(200));
// Add the second watermark
XWPFParagraph waterMark2 = document.createParagraph();
waterMark2.setAlignment(ParagraphAlignment.CENTER);
waterMark2.setVerticalAlignment(TextAlignment.CENTER);
// Add the watermark image
InputStream image2 = new FileInputStream("watermark2.png");
byte[] bytes2 = IOUtils.toByteArray(image2);
XWPFRun run2 = waterMark2.createRun();
run2.addPicture(new ByteArrayInputStream(bytes2), XWPFDocument.PICTURE_TYPE_PNG, "watermark2.png", Units.toEMU(200), Units.toEMU(200));
// Save the document
FileOutputStream fos = new FileOutputStream("output.docx");
document.write(fos);
fos.close();
document.close();
System.out.println("Watermarks added successfully.");
} catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
e.printStackTrace();
}
}
}
```
该代码将打开名为“input.docx”的Word文档,添加两个水印,并将其保存为名为“output.docx”的新文档。要添加更多的水印,可以使用类似的代码,在文档中创建新的段落并添加图像。
阅读全文