public static boolean waterMark(String inputFile, String outputFile, String waterMarkName)throws IOException { try { //inputFile = new String(inputFile.getBytes("UTF-8"),"UTF-8"); BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 使用系统字体 String inputFileName = inputFile.substring(inputFile.lastIndexOf("/")+1);
inputFileName = URLEncoder.encode(inputFileName, "utf-8"); inputFileName = StringUtils.replace(inputFileName, "+", "%20"); //inputFileName.replace("+","%20"); //response.addHeader("Content-Disposition", "attachment;inputFileName=" + inputFileName); //inputFileName = URLEncoder.encode(inputFileName, "utf-8").replaceAll("\+", "%2B").replaceAll("\s", " "); //inputFileName = URLDecoder.decode(inputFileName, "utf-8"); //inputFileName = new String(inputFileName.getBytes(),"ISO-8859-1"); //处理文件名有中文问题 // try { // if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) { // inputFileName= URLEncoder.encode(inputFileName, "UTF-8"); // } else { // inputFileName= new String(inputFileName.getBytes(),"ISO-8859-1"); // } // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // //最后加双引号处理名称中间有空格问题 // response.setHeader("Content-Disposition","attachment;filename=""+inputFileName+"""); inputFile = inputFile.substring(0,inputFile.lastIndexOf("/"))+"/"+inputFileName; URL url = new URL(inputFile); InputStream file = url.openStream(); PdfReader reader = new PdfReader(file); System.out.print("reader"+reader); File fileOut = new File(outputFile); if (!fileOut.exists()) { // 先得到文件的上级目录,并创建上级目录,在创建文件 fileOut.getParentFile().mkdir(); fileOut.createNewFile(); } //Field f = PdfReader.class.getDeclaredField("ownerPasswordUsed"); //f.setAccessible(true); //f.set(reader, Boolean.TRUE); PdfStamper stamper = new PdfStamper(reader, new BufferedOutputStream(new FileOutputStream(fileOut))); //这里的字体设置比较关键,这个设置是支持中文的写法 int total = reader.getNumberOfPages() + 1; PdfContentByte under; Rectangle pageRect = null; String [] content = waterMarkName.split(" "); for (int i = 1; i < total; i++) { pageRect = stamper.getReader(). getPageSizeWithRotation(i); // 计算水印X,Y坐标 float x = pageRect.getWidth()/2; float y = pageRect.getHeight()/2; // 获得PDF最顶层 under = stamper.getOverContent(i); under.saveState(); // set Transparency PdfGState gs = new PdfGState(); // 设置透明度为0.2 gs.setFillOpacity(0.1f); under.setGState(gs); under.restoreState(); under.beginText(); under.setFontAndSize(base, 55); under.setColorFill(BaseColor.GRAY); // 水印文字成35度角倾斜 under.showTextAligned(Element.ALIGN_CENTER ,content[0], x, y, 35); under.showTextAligned(Element.ALIGN_CENTER ,content[1], x+30, y-50, 35); // 添加水印文字 under.endText(); under.setLineWidth(1f); under.stroke(); } stamper.close(); file.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }