栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java文件下载并且添加水印效果

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java文件下载并且添加水印效果

文件下载公共类

package com.sw.api.utils;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class ExportUtil {


    public void export(HttpServletResponse response) throws IOException {
        //根据文件流创建XSSFWorkbook对象
        XSSFWorkbook wb = new XSSFWorkbook();
        //XSSFSheet sheet = wb.getSheetAt(0);
        XSSFSheet sheet = wb.createSheet("Sheet1");
        sheet.setDefaultColumnWidth(16);//设置默认列宽
        sheet.setDefaultRowHeightInPoints(20);//设置默认行高
        //设置样式;
        XSSFCellStyle style = wb.createCellStyle();
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HorizontalAlignment.CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        XSSFRow rowRowName = sheet.createRow(0);
        //设置水印
        WaterMarkUtil.putWaterMarkToExcel(wb);

        // 将列头设置到sheet的单元格中
        String[] rowName =  new String[] {"id", "年龄", "名称"};
        for(int n=0;n dataList = new ArrayList();
        Object[] objs1 = new Object[rowName.length];
        objs1[0] = "1";
        objs1[1] = "12";
        objs1[2] = "张三";
        dataList.add(objs1);
        Object[] objs2 = new Object[rowName.length];
        objs2[0] = "2";
        objs2[1] = "22";
        objs2[2] = "李四";
        dataList.add(objs2);

        //将查询出的数据设置到sheet对应的单元格中
        for(int i = 0;i < dataList.size();i++){
            Object[] obj = dataList.get(i);
            XSSFRow row = sheet.createRow(i+1);
            //row.setHeight((short) (25 * 20));
            for(int j = 0; j < obj.length; j++){
                Cell cell = null;
                cell = row.createCell(j);
                if(!"".equals(obj[j]) && obj[j] != null){
                    cell.setCellValue(obj[j].toString());
                    cell.setCellStyle(style);
                }
            }
        }

        //输出Excel文件
        OutputStream output= response.getOutputStream();
        response.reset();
        String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String fileName = date + ".xlsx";
        response.setHeader("Content-Disposition","attachment; filename=" +new String(fileName.getBytes("UTF-8"), "iso-8859-1")+".xlsx");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        wb.write(output);
        output.close();
    }

}

添加水印公共类

package com.sw.api.utils;

import org.apache.poi.ooxml.POIXMLdocumentPart;
import org.apache.poi.openxml4j.opc.PackagePartName;
import org.apache.poi.openxml4j.opc.PackageRelationship;
import org.apache.poi.openxml4j.opc.TargetMode;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFRelation;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.imageio.ImageIO;
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.ByteArrayOutputStream;
import java.io.IOException;

public class WaterMarkUtil {

    private static BufferedImage createWaterMark(String[] content) {
        Integer width = 420;//水印宽度
        Integer height = 380;//水印高度
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// 获取bufferedImage对象
        String fontType = "STSongti-SC-Bold";
        Integer fontStyle = Font.BOLD;
        Integer fontSize = 35;
        Font font = new Font(fontType, fontStyle, fontSize);
        Graphics2D g2d = image.createGraphics(); // 获取Graphics2d对象
        image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g2d.dispose();
        g2d = image.createGraphics();
        g2d.setColor(new java.awt.Color(0, 0, 0, 50));
        g2d.setStroke(new BasicStroke(1));
        g2d.setFont(font);
        g2d.rotate(Math.toRadians(-30),(double) image.getWidth() / 2, (double) image.getHeight() / 2);//设置旋转角度

        FontRenderContext context = g2d.getFontRenderContext();
        //找到水印信息中最长的
        int contentLindex = 0;
        int contentLength = content[0].length();

        for (int i = 0; i < content.length; i++) {
            if (content[i].length()>contentLength) {
                contentLindex = i;
            }
        }
        Rectangle2D bounds = font.getStringBounds(content[contentLindex], context);
        double x = (width - bounds.getWidth()) / 2;
        double y = (height - bounds.getHeight()) / 2;
        double ascent = -bounds.getY();
        double baseY = y + ascent;
        // 写入水印文字原定高度过小,所以累计写水印,增加高度
        for (int i = 0; i < content.length; i++) {
            g2d.drawString(content[i], (int)x, (int)baseY);// 画出字符串
            baseY = baseY + font.getSize();
        }

        // 设置透明度
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1F));
        g2d.dispose();
        return image;
    }

    public static void putWaterMarkToExcel(XSSFWorkbook workbook) throws IOException {
        BufferedImage image = createWaterMark(new String[]{"水印名称logo"});
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image, "png", os);
        int pictureIdx = workbook.addPicture(os.toByteArray(), Workbook.PICTURE_TYPE_PNG);
        POIXMLdocumentPart poixmldocumentPart = workbook.getAllPictures().get(pictureIdx);
        XSSFSheet sheet = workbook.getSheetAt(0);
        PackagePartName ppn = poixmldocumentPart.getPackagePart().getPartName();
        String relType = XSSFRelation.IMAGES.getRelation();
        PackageRelationship pr = sheet.getPackagePart().addRelationship(ppn, TargetMode.INTERNAL, relType, null);
        sheet.getCTWorksheet().addNewPicture().setId(pr.getId());
    }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/703943.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号