1. 程式人生 > >pdf檔案下載水印新增的中文與空格問題解決

pdf檔案下載水印新增的中文與空格問題解決

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; } }