java 给word文件添加图片水印
时间: 2023-12-09 15:02:23 浏览: 114
您好,可以使用 Apache POI 库来操作 Word 文档,在 Word 文档中添加图片水印。以下是示例代码:
```
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class WatermarkUtil {
/**
* 添加图片水印到 Word 文档
* @param inputPath 输入 Word 文件路径
* @param outputPath 输出 Word 文件路径
* @param imageUrl 水印图片地址
* @throws IOException
*/
public static void addImageWatermark(String inputPath, String outputPath, String imageUrl) throws IOException {
XWPFDocument document = new XWPFDocument(FileUtils.openInputStream(new File(inputPath)));
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
BufferedImage image = ImageIO.read(new URL(imageUrl));
int width = image.getWidth();
int height = image.getHeight();
int logoWidth = 200;
int logoHeight = logoWidth * height / width; // 等比例缩放
// 创建图片,并将图片缩放到指定大小
String filename = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
Picture picture = run.addPicture(IOUtils.toByteArray(new URL(imageUrl).openStream()), Workbook.PICTURE_TYPE_JPEG, filename, logoWidth, logoHeight);
// 设置图片水印效果
picture.resize();
picture.setLineWidth(0.5);
picture.getLine().setCompoundLineType(Drawing.PresetLineType.DASHED);
picture.setFillColor(Color.white);
picture.setLineDash(new float[] { 1.0f, 1.0f });
// 将图片水印应用到每一页
for (XWPFParagraph p : document.getParagraphs()) {
for (XWPFRun r : p.getRuns()) {
for (int i = 0; i < r.getCTR().getFldSimpleList().size(); i++) {
if (r.getCTR().getFldSimpleList().get(i).getInstr().contains("PAGE")) {
int pageNumber = Integer.parseInt(r.getCTR().getFldSimpleList().get(i).getInstr().replaceAll("\\D", ""));
Drawing drawing = r.getCTR().addNewDrawing();
drawing.setAnchor(picture.getAddress(pageNumber - 1));
}
}
}
}
// 输出 Word 文件
FileOutputStream out = new FileOutputStream(outputPath);
document.write(out);
out.close();
document.close();
}
}
```
使用时,可以通过调用 `addImageWatermark` 方法传入 Word 文件路径和水印图片地址。例如:
```
WatermarkUtil.addImageWatermark("D:\\input.docx", "D:\\output.docx", "http://xxx.com/watermark.jpg");
```
请注意,该示例代码仅适用于 Word 文档,并且需要下载 Apache POI 库才能运行。另外,本AI只是一个语言模型,无法接收您的任何要求,也无法泄露您的任何信息。
阅读全文