根据IO流的处理,简单思想是在上传主机建立一个临时文件 存放加水印之后的新PDF文件,上传服务器完成之后 删除临时文件
具体代码如下:
1、针对普通的文件上传 如果知道本地路径可以通过简单方法加水印
public static void main(String[] args) throws DocumentException, IOException { // // 要输出的pdf文件 // BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("D:/conc.pdf"))); // String waterMarkName = "美丽修行"; // // 将pdf文件先加水印然后输出 setWatermark(bos, "D:/1.pdf", waterMarkName); // setImgWatermark(bos, "D:/1.pdf","D:/111.png"); addTextWaterMark("D:/conc1.pdf","D:/conc2.pdf",waterMarkName); // 添加水印之后的文件 如果不存在会新建 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("D:/out.pdf"))); // 将pdf文件先加水印然后输出 setImgWatermark(bos, "D:/conc2.pdf", "D:/11.png"); }
1.1、添加文本水印
public static void setWatermark(BufferedOutputStream bos, String input, String waterMarkName) throws DocumentException, IOException { PdfReader reader = new PdfReader(input); PdfStamper stamper = new PdfStamper(reader, bos); int total = reader.getNumberOfPages() + 1; PdfContentByte content; BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED); PdfGState gs = new PdfGState(); Rectangle pageRect = null; //初始化水印label JLabel label = new JLabel(); FontMetrics metrics; int textH = 0; int textW = 0; label.setText(waterMarkName); metrics = label.getFontMetrics(label.getFont()); textH = metrics.getHeight(); textW = metrics.stringWidth(label.getText()); for (int i = 1; i < total; i++) { pageRect = reader.getPageSizeWithRotation(i); content = stamper.getOverContent(i);// 在内容上方加水印 // content = stamper.getUnderContent(i);//在内容下方加水印 //設置透明度 gs.setFillOpacity(0.001f); // content.setGState(gs); content.beginText(); content.setColorFill(BaseColor.LIGHT_GRAY); content.setFontAndSize(base, 20); //