csv、image、excel、PPT、word文件添加水印

## 最近有一个需求,需要给csv文件添加水印,真是无穷无尽的需求啊,所以就搜索整理了一下:

话不多说,直接开干:

1. 引入pom:

我使用的${poi.version}是3.17版本

      <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>${poi.version}</version>
      </dependency>
      <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>${poi.version}</version>
      </dependency>
      <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml-schemas</artifactId>
        <version>3.17</version>
      </dependency>
      <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-scratchpad</artifactId>
        <version>${poi.version}</version>
      </dependency>
      <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml-full</artifactId>
        <version>5.0.0</version>
      </dependency>

2. 创建工具类

package com.lkl.commons.utils;


import java.awt.*;
import java.awt.Font;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;

/*import com.spire.doc.PictureWatermark;
import com.spire.doc.TextWatermark;
import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;*/
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRelation;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * 当前pom只引入了给csv,excel,image加水印的依赖,如需使用其他,
 * 请下载spire.office.free-5.3.1.jar 引入pom后即可
 */

/*<dependency>
      <groupId>e-iceblue</groupId>
      <artifactId>spire.office.free</artifactId>
      <version>5.3.1</version>
      <scope>system</scope>
      <systemPath>D:\\jars\\spire.office.free-5.3.1.jar</systemPath>
    </dependency>*/
public class WaterMarkUtils {

    /**
     * 图片添加文字水印
     *
     * @param waterMark 水印内容
     * @param path 需要加水印的附件地址
     */
    public static void setWaterMarkToImage(String waterMark, String path) {
        String down_path = getOutputPath(path);
        InputStream is = null;
        OutputStream os = null;
        try {
            // 1、源图片
            Image srcImg = ImageIO.read(new File(path));
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
            // 2、得到画笔对象
            Graphics2D g = buffImg.createGraphics();
            // 3、设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);
            // 4、设置水印旋转
            g.rotate(Math.toRadians(45), buffImg.getWidth() / 2, buffImg.getHeight() / 2);
            // 5、设置水印文字颜色
            g.setColor(Color.blue);
            // 6、设置水印文字Font
            g.setFont(new Font("宋体", Font.BOLD, buffImg.getHeight() / 5));
            // 7、设置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.3f));
            // 8、第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)
            g.drawString(waterMark, buffImg.getWidth() / 3, buffImg.getHeight() / 4);
            // 9、释放资源
            g.dispose();
            // 10、图片后缀
            String suffix = path.substring(path.lastIndexOf(".") + 1);
            // 11、生成图片
            os = new FileOutputStream(down_path);
            ImageIO.write(buffImg, suffix, os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (null != os) {
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * PPT添加动态文字水印
     *
     * @param waterMark 水印内容
     * @param path 需要加水印的附件地址
     */
    /*public static void setWaterMarkToPpt(String waterMark, String path) throws Exception {
        // 1、加载PPT源文档
        Presentation ppt = new Presentation();
        ppt.loadFromFile(path);
        String down_path = getOutputPath(path);
        // 2、遍历ppt每一页
        for (int p = 0; p < ppt.getSlides().size(); p++) {
            // 3、设置文本水印文本宽和高
            int width = 300;
            int height = 100;
            // 4、起始坐标
            float x = 10;
            float y = 40;
            ISlide slide = ppt.getSlides().get(p);
            for (int i = 0; i < 4; i++) {
                for (int j = 0; j < 4; j++) {
                    // 5、绘制文本,设置文本格式并将其添加到幻灯片
                    Rectangle2D.Double rect = new Rectangle2D.Double(x, y, width, height);
                    IAutoShape shape = slide.getShapes().appendShape(com.spire.presentation.ShapeType.RECTANGLE, rect);
                    shape.getFill().setFillType(FillFormatType.NONE);
                    shape.getShapeStyle().getLineColor().setColor(Color.white);
                    shape.setRotation(-45);
                    shape.getLocking().setSelectionProtection(true);
                    shape.getLine().setFillType(FillFormatType.NONE);
                    shape.getTextFrame().setText(waterMark);
                    shape.setShapeArrange(ShapeAlignmentEnum.ShapeArrange.SendToBack);
                    PortionEx textRange = shape.getTextFrame().getTextRange();
                    textRange.getFill().setFillType(FillFormatType.SOLID);
                    textRange.getFill().getSolidColor().setColor(new Color(238, 130, 238));
                    textRange.setFontHeight(20);
                    x += (100 + ppt.getSlideSize().getSize().getWidth() / 6);
                }
                x = 30;
                y += (100 + ppt.getSlideSize().getSize().getHeight() / 7);
            }
        }

        // 6、保存文档
        ppt.saveToFile(down_path, FileFormat.PPTX_2016);
        ppt.dispose();

    }*/

    /**
     * docx、doc、wps、wpt、rtf添加文字水印
     *
     * @param water_mark 水印内容
     * @throws Exception
     */
    /*public static void setWaterMarkToWps(String water_mark, String path) throws Exception {
        String down_path = getOutputPath(path);
        com.spire.doc.Document doc = new com.spire.doc.Document();
        doc.loadFromFile(path);
        //设置water_mark
        TextWatermark txtWatermark = new TextWatermark();
        txtWatermark.setText(water_mark);
        txtWatermark.setFontSize(75);
        txtWatermark.setColor(Color.red);
        txtWatermark.setLayout(com.spire.doc.documents.WatermarkLayout.Diagonal);
        doc.getSections().get(0).getDocument().setWatermark(txtWatermark);
        doc.saveToFile(down_path, com.spire.doc.FileFormat.Docx);

    }*/

    /**
     * docx、doc、wps、wpt、rtf添加图片水印
     *
     * @param water_mark 水印内容
     * @throws Exception
     */
    /*public static void setWaterMarkToWps2(String water_mark, String path) throws Exception {
        String down_path = getOutputPath(path);
        com.spire.doc.Document doc = new com.spire.doc.Document();
        doc.loadFromFile(path);
        //设置water_mark
        PictureWatermark picture = new PictureWatermark();
        picture.setPicture(water_mark);
        picture.setScaling(70);
        picture.isWashout(false);
        doc.setWatermark(picture);
        doc.saveToFile(down_path, com.spire.doc.FileFormat.Docx);

    }*/

    /**
     * xlsx、xls、et、csv添加水印
     *
     * @param waterMark 水印内容
     * @param path 需要加水印的附件地址
     * @throws Exception
     */
    public static void setWaterMarkToExcel(String waterMark, String path) throws Exception {
        String path_down = getOutputPath(path);
        XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(path));
        // 1、添加水印
        ByteArrayOutputStream byteArrayOutputStream = createWaterMark(waterMark);
        int pictureIdx = wb.addPicture(byteArrayOutputStream.toByteArray(), Workbook.PICTURE_TYPE_PNG);
        // 2、遍历sheet 给每个sheet 添加水印
        for (int i = 0; i < wb.getNumberOfSheets(); i++) {
            XSSFSheet sheet = wb.getSheetAt(i);
            String rID = sheet.addRelation(null, XSSFRelation.IMAGES, wb
                    .getAllPictures().get(pictureIdx)).getRelationship().getId();
            sheet.getCTWorksheet().addNewPicture().setId(rID);
        }
        // 3、输出添加水印后的文件
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        wb.write(bos);
        wb.close();

        byte[] content = bos.toByteArray();
        OutputStream out = null;
        out = new FileOutputStream(path_down);
        out.write(content);
        bos.close();
        out.close();
    }

    public static void main(String[] args) throws Exception {
        WaterMarkUtils.setWaterMarkToExcel("这是水印内容", "C:\\Users\\admin\\Desktop\\各种文件\\模版_ce.csv");
        WaterMarkUtils.setWaterMarkToImage("这是水印内容", "C:\\Users\\admin\\Desktop\\各种文件\\照片\\桌面壁纸.jpg");
        //WaterMarkUtils.setWaterMarkToPpt("这是水印内容", "C:\\Users\\admin\\Desktop\\各种文件\\简历.pptx");
        //WaterMarkUtils.setWaterMarkToWps("这是水印内容", "C:\\Users\\admin\\Desktop\\各种文件\\2024-11-18.docx");
        //WaterMarkUtils.setWaterMarkToWps2("C:\\Users\\admin\\Desktop\\各种文件\\照片\\桌面壁纸.jpg", "C:\\Users\\admin\\Desktop\\各种文件\\2024-11-18.docx");
    }



    /**
     * 给sheet 加水印
     *
     * @param content 水印文字
     */
    private static ByteArrayOutputStream createWaterMark(String content) throws IOException {
        int width = 200;
        int height = 150;
        // 1、获取bufferedImage对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Font font = new Font("微软雅黑", Font.BOLD, 20);
        // 2、获取Graphics2d对象
        Graphics2D g2d = image.createGraphics();
        image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g2d.dispose();
        g2d = image.createGraphics();
        // 3、设置字体颜色和透明度,最后一个参数为透明度
        g2d.setColor(new Color(0, 0, 0, 20));
        // 4、设置字体
        g2d.setStroke(new BasicStroke(1));
        // 5、设置字体类型 加粗 大小
        g2d.setFont(font);
        // 6、设置倾斜度
        g2d.rotate(-0.5, (double) image.getWidth() / 2, (double) image.getHeight() / 2);
        FontRenderContext context = g2d.getFontRenderContext();
        Rectangle2D bounds = font.getStringBounds(content, context);
        double x = (width - bounds.getWidth()) / 2;
        double y = (height - bounds.getHeight()) / 2;
        double ascent = -bounds.getY();
        double baseY = y + ascent;
        // 7、写入水印文字原定高度过小,所以累计写水印,增加高度
        g2d.drawString(content, (int) x, (int) baseY);
        // 8、设置透明度
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
        // 9、释放对象
        g2d.dispose();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // 10、输出
        ImageIO.write(image, "png", os);
        return os;
    }

    /**
     * 获取 添加水印后的文件路径
     *
     * @param input_path 需要加水印的附件地址
     * @return
     */
    private static String getOutputPath(String input_path) {
        // 1、生成水印后的PDF路径
        String path = input_path.substring(0, input_path.lastIndexOf(".")) + "_水印.";
        // 2、文件后缀
        String suffix = input_path.substring(input_path.lastIndexOf(".") + 1);
        // 3、返回添加水印后的文件路径
        return path + suffix;
    }
}

 目前上面引入的pom可以支持没有注释的文件添加水印;如果需要其他注释掉的功能,需要根据描述添加jar:

/*<dependency>
      <groupId>e-iceblue</groupId>
      <artifactId>spire.office.free</artifactId>
      <version>5.3.1</version>
      <scope>system</scope>
      <systemPath>D:\\jars\\spire.office.free-5.3.1.jar</systemPath>
    </dependency>*/

这个包比较好找,但是不知道为什么我直接拉不下来。。

Sonatype Nexus Repository

上面的下载链接,点进去搜索下载,然后本地引入,放开注释,其他的就可以使用啦!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值