阿里云OSS下载pdf文件,并在pdf文件上添加水印 - 传说中的汽水枪

时间:2024-02-29 15:35:18

阿里云OSS下载pdf文件,并在pdf文件上添加水印

代码: 兵马未动,粮草先行

作者: 传说中的汽水枪

如有错误,请留言指正,欢迎一起探讨.

转载请注明出处.

 

公司要求从阿里云OSS下载pdf文件并且需要添加水印.

因此这里总结一下.

首先添加了一个FileUploadUtil.java文件:

    /**OSSClient*/
    private static OSSClient CLIENT;

    public static InputStream getInputStreamFromOSS(String ossFileName) {
        String parentDirectory = ossFileName.substring(0, 8) + "/";
        String fileId = "你自己的fileId";
        CLIENT = new OSSClient(ENDPOINT, ACCESSKEYID, ACCESSKEYSECRET);
        OSSObject ossObject = CLIENT.getObject(BUCKETNAME, fileId + ossFileName);
        InputStream inputStream = ossObject.getObjectContent();
        return inputStream;
    }

    public static void clientShutdown() {
        if (CLIENT != null) {
            CLIENT.shutdown();
        }
    }

在controller层先实现下载文件功能:

    @ResponseBody
    @RequestMapping(value = "/downloadFromOSS", method = RequestMethod.GET)
    public void downloadFromOSS(String fileName, HttpServletResponse response, HttpServletRequest request) {
        try {
            String dataString = DateUtil.date2Str(new Date(), "yyyy-MM-dd-HH-mm-ss-SSS");
            String destFileName = dataString + ".pdf";
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + destFileName);
            // 获取outputStream
            OutputStream outputStream = response.getOutputStream();
            // 获取inputStream
            InputStream inputStream = FileUploadUtil.getInputStreamFromOSS(fileName);
            // 下载文件
            byte[] bytes = new byte[2048];
            int length;
            while ((length = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, length);
            }
            outputStream.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            FileUploadUtil.clientShutdown();
        }
    }

实现下载并添加水印:

    @ResponseBody
    @RequestMapping(value = "/downloadWatermarkFile", method = RequestMethod.GET)
    public void downloadWatermarkFile(String fileName, HttpServletResponse response, HttpServletRequest request) {
        try {
            String dataString = DateUtil.date2Str(new Date(), "yyyy-MM-dd-HH-mm-ss-SSS");
            String destFileName = dataString + ".pdf";
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + destFileName);
            // 获取outputStream
            OutputStream outputStream = response.getOutputStream();
            // 获取inputStream
            InputStream inputStream = FileUploadUtil.getInputStreamFromOSS(fileName);

            // 添加水印的时候,就已经在outputStream写入了
            PdfReader reader = new PdfReader(inputStream);
            PdfStamper stamper = new PdfStamper(reader, outputStream);
            int total = reader.getNumberOfPages() + 1;
            PdfContentByte content;
            BaseFont base = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            PdfGState gs = new PdfGState();
            for (int i = 1; i < total; i++) {
                content = stamper.getOverContent(i);// 在内容上方加水印
                //content = stamper.getUnderContent(i);//在内容下方加水印
                gs.setFillOpacity(0.2f);
                content.setGState(gs);
                content.beginText();
                content.setColorFill(com.itextpdf.text.BaseColor.LIGHT_GRAY);
                content.setFontAndSize(base, 50);
                content.setTextMatrix(70, 200);
                //将文字显示在pdf页面中
                // content.showTextAligned(Element.ALIGN_CENTER, "国际财富管理协会(中国)!", 300,350, 55);
                //设置文字颜色
                content.setColorFill(com.itextpdf.text.BaseColor.BLACK);
                //设置文字大小
                content.setFontAndSize(base, 8);
                //将内容显示在pdf底部
                String waterMarkName = "111111";
                content.showTextAligned(Element.ALIGN_CENTER, "下载时间:" + waterMarkName + "", 300, 10, 0);
                content.endText();
            }
            stamper.close();
            outputStream.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            FileUploadUtil.clientShutdown();
        }
    }

 

OK 解决问题.