Java word文档生成水印 代码
时间: 2023-03-01 14:17:46 浏览: 108
Here is an example Java code that generates a watermark on a Word document:
```
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class WatermarkGenerator {
public static void main(String[] args) {
try {
// Open the Word document
FileInputStream inputStream = new FileInputStream("sample.docx");
XWPFDocument doc = new XWPFDocument(inputStream);
// Iterate over each paragraph
for (XWPFParagraph paragraph : doc.getParagraphs()) {
XWPFRun run = paragraph.createRun();
run.setText("SAMPLE DOCUMENT");
run.setFontSize(36);
run.setColor("999999");
run.setFontFamily("Courier");
run.setTextPosition(100);
run.setBold(true);
paragraph.setAlignment(XWPFParagraph.Alignment.CENTER);
}
// Save the document with the watermark
FileOutputStream outputStream = new FileOutputStream("sample_with_watermark.docx");
doc.write(outputStream);
outputStream.close();
inputStream.close();
System.out.println("Watermark added successfully!");
} catch (Exception e) {
System.out.println("Error adding watermark: " + e.getMessage());
}
}
}
```
Note that this code uses the Apache POI library to manipulate the Word document. You'll need to include the POI jar files in your project classpath in order to use this code.
阅读全文