本文实例为大家分享了java pdf加水印的具体代码,供大家参考,具体内容如下
引入依赖
com.itextpdf.tool xmlworker 5.5.10 com.itextpdf itextpdf 5.5.10
‘/static/fonts/SIMYOU.TTF' 字体 本机没有的话, 可以百度下载
/** * pdf 加水印 * * @return */ public byte[] pdfAddWaterMark(byte[] byes) { String fileName = UUID.randomUUID().toString() + ".pdf"; String courseFile = ""; try { // 第二种:获取项目路径 D:\git\daotie\daotie //生成临时文件 , 读取完删除 File directory = new File("");// 参数为空 courseFile = directory.getCanonicalPath() + "/"; } catch (IOException e) { e.printStackTrace(); } byte[] returnBytes = null; // 待加水印的文件 PdfReader reader = null; PdfStamper stamper = null; // ByteArrayOutputStream baos = null; FileOutputStream os = null; try { reader = new PdfReader(byes); // 加完水印的文件 // baos = new ByteArrayOutputStream(); // stamper = new PdfStamper(reader, baos); // 加完水印的文件 os = new FileOutputStream(courseFile + fileName); stamper = new PdfStamper(reader, os); int total = reader.getNumberOfPages() + 1; PdfContentByte content; // BaseFont fOnt= BaseFont.createFont(); BaseFont basefOnt= BaseFont.createFont("/static/fonts/SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); //这里的字体设置比较关键,这个设置是支持中文的写法 /*BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 使用系统字体*/ /*//设置透明度 PdfGState gs = new PdfGState(); gs.setFillOpacity(1f); gs.setStrokeOpacity(1f);*/ PdfContentByte under; com.itextpdf.text.Rectangle pageRect = null; // 循环对每页插入水印 for (int i = 1; i
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。