/** * 添加文字水印 * @param srcFile 待加水印文件 * @param destFile 加水印后输出文件 * @param text 文本内容 * @throws Exception */ public static void addWaterMark(String srcFile, String destFile, String text) throws Exception { // 待加水印的文件 PdfReader reader = new PdfReader(srcFile); // 加完水印的文件 PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile)); stamper.setEncryption(USER_PASS.getBytes(),OWNER_PASS.getBytes(),1,false); int total = reader.getNumberOfPages() + 1; PdfContentByte content; // 设置透明度 PdfGState gs = new PdfGState(); gs.setFillOpacity(0.05f); // 设置字体 BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED); // 循环对每页插入水印 for (int i = 1; i < total; i++) { // 水印的起始 content = stamper.getOverContent(i); content.setGState(gs); content.setFontAndSize(base, 28); // 开始 content.beginText(); // 设置颜色 默认为黑色 content.setColorFill(BaseColor.BLACK); // 开始写入水印 content.showTextAligned(Element.ALIGN_MIDDLE, text, 100, 50, 30); content.showTextAligned(Element.ALIGN_MIDDLE, text, 100, 250, 30); content.showTextAligned(Element.ALIGN_MIDDLE, text, 100, 450, 30); content.showTextAligned(Element.ALIGN_MIDDLE, text, 100, 650, 30); content.showTextAligned(Element.ALIGN_MIDDLE, text, 300, 50, 30); content.showTextAligned(Element.ALIGN_MIDDLE, text, 300, 250, 30); content.showTextAligned(Element.ALIGN_MIDDLE, text, 300, 450, 30); content.showTextAligned(Element.ALIGN_MIDDLE, text, 300, 650, 30); content.endText(); } stamper.close(); }
itext5 PDF添加水印
最新推荐文章于 2024-03-17 14:59:55 发布