spring boot文件下载加水印(pdf,word,pdf,照片,excel)

<repositories>
        <repository>
            <id>com.e-iceblue</id>
            <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
        </repository>
    </repositories>

<!--        pdf加水印-->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13</version>
        </dependency>

    <!--办公文件加水印-->
        <dependency>
            <groupId>e-iceblue</groupId>
            <artifactId>spire.office.free</artifactId>
            <version>5.2.0</version>
        </dependency>

1.首先导入依赖

2.创建工具类

3.创建加入水印,(我这里水印是图片)

 public static BufferedImage createWatermarkImage(WaterMarkContent watermark) {
        if (watermark == null) {
            watermark = new WaterMarkContent();
            watermark.setEnable(true);
            watermark.setText(SecurityUtils.getLoginUser().getUser().getNickName());
            watermark.setColor("#C5CBCF");
            watermark.setDateFormat("yyyy-MM-dd HH:mm");
        }
        String[] textArray = watermark.getText().split(",");
        Font font = new Font("microsoft-yahei", Font.PLAIN, 20);
        Integer width = 300;
        Integer height = 100;

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 背景透明 开始
        Graphics2D g = image.createGraphics();
        image = g.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g.dispose();
        // 背景透明 结束
        g = image.createGraphics();
        // 设定画笔颜色
        g.setColor(new Color(Integer.parseInt(watermark.getColor().substring(1), 16)));
        // 设置画笔字体
        g.setFont(font);
        // 设定倾斜度
        g.shear(0.1, -0.26);

        // 设置字体平滑
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        int y = 50;
        for (int i = 0; i < textArray.length; i++) {
            // 画出字符串
            g.drawString(textArray[i], 0, y);
            y = y + font.getSize();
        }
        // 画出字符串
        g.drawString(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date()), 0, y);
        // 释放画笔
        g.dispose();
        return image;
    }

然后就是生成各种文件水印了


    /**
     * excel文件添加水印图片
     *
     * @param workbook
     * @param bfi
     * @param os
     * @throws Exception
     */
    public static void setWaterMarkToExcel(XSSFWorkbook workbook, BufferedImage bfi, OutputStream os) throws Exception {

        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
        ImageIO.write(bfi, "png", byteArrayOut);
        int pictureIdx = workbook.addPicture(byteArrayOut.toByteArray(), Workbook.PICTURE_TYPE_PNG);
        //add relation from sheet to the picture data
        POIXMLDocumentPart poixmlDocumentPart = workbook.getAllPictures().get(pictureIdx);
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            XSSFSheet xssfSheet = workbook.getSheetAt(i);
            PackagePartName ppn = poixmlDocumentPart.getPackagePart().getPartName();
            String relType = XSSFRelation.IMAGES.getRelation();
            PackageRelationship pr = xssfSheet.getPackagePart().addRelationship(ppn, TargetMode.INTERNAL, relType, null);
            xssfSheet.getCTWorksheet().addNewPicture().setId(pr.getId());
        }
        workbook.write(os);
    }

    /**
     * word文档设置水印图片
     *
     * @param filePath 文件路径
     * @param bfi      bfi
     * @throws IOException ioexception
     */
    public static String setWaterMarkToWord(String filePath, BufferedImage bfi) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(bfi, "png", out);
        Document document = new Document();
        document.loadFromFile(filePath);
        PictureWatermark picture = new PictureWatermark();
        InputStream input = new ByteArrayInputStream(out.toByteArray());
        //设置图片
        picture.setPicture(input);
        //设置图片大小
        picture.setScaling(SIZE);
        //是否冲刷,true->图片色彩变淡,false->原色彩
        picture.isWashout(true);
        //保存文档
        document.setWatermark(picture);
        String downLoadPath = filePath.substring(0, filePath.lastIndexOf("/") + 1) + System.currentTimeMillis() + "_" + StrUtil.subAfter(filePath, "/", true);
        document.saveToFile(downLoadPath, FileFormat.Docx);

        return downLoadPath;
    }

    /**
     *   pdf加水印图片
     *
     * @param filePath 文件路径
     * @param bfi      bfi
     * @return {@link String}
     * @throws IOException       ioexception
     * @throws DocumentException 文件异常
     */
    public static String setWaterMarkToPdf(String filePath, BufferedImage bfi) throws IOException, DocumentException {
        PdfReader reader=new PdfReader(filePath);
        //保存路径
        String downloadPath = filePath.substring(0, filePath.lastIndexOf("/") + 1) +
                System.currentTimeMillis() + "_" + StrUtil.subAfter(filePath, "/", true);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(downloadPath));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(bfi, "png", out);
        //将图片放入pdf中
        com.itextpdf.text.Image image= com.itextpdf.text.Image.getInstance(out.toByteArray());
        //获取pdf页数
        int num = reader.getNumberOfPages();
        com.itextpdf.text.Rectangle pageSize;
        float width = 0f;
        float height = 0f;
        int x = 0;
        for (int i = 1; i < num; i++) {
            //得到页面大小
            x++;
            if (x == 1) {
                pageSize=reader.getPageSize(i);
                width=pageSize.getWidth();
                height=pageSize.getHeight();
            }
            //水印图片设置在内容之上,之下用getUnderContent
            PdfContentByte pdfContentByte = stamper.getOverContent(i);
            //设置图片的位置,参数Image.UNDERLYING是作为文字的背景显示。
            image.setAlignment(com.itextpdf.text.Image.UNDEFINED);
            //设置图片的绝对位置
            image.setAbsolutePosition((width - image.getWidth()) / 2,(height -image.getHeight()) / 2 );
             pdfContentByte.addImage(image);
        }
        stamper.close();
        reader.close();
        return downloadPath;
    }

    /**
     * ppt加水印图片
     *
     * @param filePath 文件路径
     * @param bfi      bfi
     * @return {@link String}
     */
    public static String setWaterMarkToPpt(String filePath,BufferedImage bfi) throws Exception {
        Presentation presentation=new Presentation();
        presentation.loadFromFile(filePath);
        //将图片转字节码
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        //将图片转字节码
        ImageIO.write(bfi, "png", out);
        //将字节码转为输入流
        InputStream input = new ByteArrayInputStream(out.toByteArray());
        IImageData image = presentation.getImages().append(input);
        //获取幻灯片背景属性,设置图片填充
        SlideCollection slides = presentation.getSlides();
        for (int i = 0; i < slides.size(); i++) {
            slides.get(i).getSlideBackground().setType(BackgroundType.CUSTOM);
            slides.get(i).getSlideBackground().getFill().setFillType(FillFormatType.PICTURE);
            slides.get(i).getSlideBackground().getFill().getPictureFill().setFillType(PictureFillType.STRETCH);
            slides.get(i).getSlideBackground().getFill().getPictureFill().getPicture().setEmbedImage(image);
        }
        //保存文档
        String downloadPath = filePath.substring(0, filePath.lastIndexOf("/") + 1) +
                System.currentTimeMillis() + "_" + StrUtil.subAfter(filePath, "/", true);
        presentation.saveToFile(downloadPath, com.spire.presentation.FileFormat.PPSX_2013);

       return downloadPath;
    }

    /**
     * 图片加水印
     *
     * @param filePath 文件路径
     * @param bfi      bfi
     * @return {@link String}
     */
    public static String setWaterMarkToImg(String filePath,BufferedImage bfi) throws IOException {
        //获取画布
        BufferedImage read=ImageIO.read(new File(filePath));
        Graphics2D graphics=read.createGraphics();

        //缩放水印图片
        int width=bfi.getWidth();
        int height=bfi.getHeight();
        //设置比例
        float f=getScale(width,height,0.5f);
        //获取缩放后的宽度
        int w= (int) (width*f);
        int h= (int) (height*f);
        //缩放图片
        Image image = bfi.getScaledInstance(w, h, Image.SCALE_SMOOTH);
        //设置透明度,0->1,逐渐不透明
        graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,ALPHA_IMG));
         //添加水印并设置在图片的右下角
        graphics.drawImage(image,read.getWidth() -w,read.getHeight()-h,null);
        //释放资源
        graphics.dispose();

        //保存图片
        String downloadPath = filePath.substring(0, filePath.lastIndexOf("/") + 1) +
                System.currentTimeMillis() + "_" + StrUtil.subAfter(filePath, "/", true);
        ImageIO.write(read, filePath.substring(filePath.lastIndexOf(".") + 1), new File(downloadPath));
        return downloadPath;
    }


    /**
     * 获得图片比例
     *
     * @param width  宽度
     * @param height 高度
     * @param f      f
     * @return float
     */
    public static float getScale(int width, int height, float f) {
        if (width > 3000) {
            f = 0.06f;
        }
        if (width > 1000 && width < 3000) {
            f = 0.1f;
        }
        if (width > 300 && width < 1000) {
            f = 0.3f;
        }
        return f;
    }

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值