pdf文件下載水印添加的中文與空格問題解決
阿新 • • 發佈:2018-12-26
buffer row exc ole lena coder pla throws float
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("\r\n"); 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; } }
pdf文件下載水印添加的中文與空格問題解決