整体思路:
1.先从阿里云把该pdf文件下载到服务器中。
2.对下载的pdf文件添加水印。
3.将加过水印的文件重新上传到阿里云。
4.删除服务器中的文件。
总处理方法:
/** * 给PDF文件添加水印 * @param file * @return */ public String addMarking(MultipartFile file){ //1.上传到本地,并重命名增加“无水印”2个字 //获取本项目的路径 File fDir=new File(System.getProperty("user.dir")); //File.separator表示根目录,比如现在就表示在D盘下。 String strFile=File.separator+"theaUpload"; //这个就是绝对路径 File myFilePath=new File(fDir,strFile); if (!myFilePath.exists()) { myFilePath.mkdir(); } String realpath = myFilePath.getAbsolutePath();//服务器中附件所在文件夹地址 //判断该文件夹否存在 如果不存在就创建新的文件路径 if(!myFilePath.exists()){ myFilePath.mkdir(); } String fileName = file.getOriginalFilename(); //服务器中源文件名称 StringBuffer sb = new StringBuffer("无水印"); sb.append(fileName); File fileNew = new File(myFilePath,sb.toString()); try {//把文件拷贝到本地 InputStream input = file.getInputStream(); if(null != input){ OutputStream output = null; try { output = new FileOutputStream(fileNew); byte[] buf = new byte[1024]; int bytesRead; while ((bytesRead = input.read(buf)) != -1) { output.write(buf, 0, bytesRead); } } finally { input.close(); output.close(); } } } catch (Exception e) { logger.error("上传文档异常"+e); return ""; } //2.加水印后保存在本地 String oldPath = realpath+File.separator+sb.toString();//无水印、重命名过的原始文件 String newPath = realpath+File.separator+fileName;//有水印,原始名字的新文件 AddWatermarkingPDF.waterMark(oldPath,newPath,markName); //3.上传阿里云 try{ InputStream inputFile = new FileInputStream(newPath); //阿里云保存地址 String filePath = OssUtil.uploadFile(fileName, inputFile, helpPath); //4.删除服务器中的2个文件 if(fileNew.isFile() && fileNew.exists()){ fileNew.delete(); } File markFile = new File(newPath); if(markFile.isFile() && markFile.exists()){ markFile.delete(); } return filePath; }catch (Exception e){ logger.error("加水印后的文件异常"+e); } return ""; }
添加水印的方法:
public static void waterMark(String inputFile,String outputFile, String waterMarkName) { try { PdfReader reader = new PdfReader(inputFile); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile)); BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED); PdfGState gs = new PdfGState(); //设置透明度 gs.setFillOpacity(0.2f); gs.setStrokeOpacity(0.3f); int total = reader.getNumberOfPages() + 1; JLabel label = new JLabel(); label.setText(waterMarkName); PdfContentByte under; for (int i = 1; i < total; i++) { under = stamper.getOverContent(i); under.saveState(); under.setGState(gs); under.beginText(); under.setFontAndSize(base, 70); under.setColorFill(BaseColor.RED);//设置水印颜色 // 水印文字成30度角倾斜 //你可以随心所欲的改你自己想要的角度 for (int y = 0; y < 10; y++) { for (int x = 0; x < 8; x++) { // 水印文字成45度角倾斜 under.showTextAligned(Element.ALIGN_LEFT , waterMarkName, 100 + 300 * x, 300 * y, 30); } } // 添加水印文字 under.endText(); } //关闭流 stamper.close(); reader.close(); } catch (Exception e) { logger.error(outputFile+"文档添加水印报错"+e); } }
上传到阿里云的方法我就不贴出来了!