嗨客网搜索
Java中PDF添加水印

在 PDF 中添加水印需要依赖 http://www.itextpdf.com/ 提供的 jar 包,我们新建 maven 项目,依赖如下:

<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13.2</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency>

代码结构如下:

08 pdf添加水印前.png

PdfWaterMarkUtil

package net.haicoder.watermark; import com.itextpdf.text.Element; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.*; import javax.swing.*; import java.awt.*; import java.io.FileOutputStream; /** * @author 嗨客网 * @description pdf 支持水印 */ public class PdfWaterMarkUtil { private static int interval = -5; /** * @param filePath 你的PDF文件地址 * @param outputFile 添加水印后生成PDF存放的地址 * @param waterMarkContent 你的水印 * @return */ public static boolean pdfWaterMark(String filePath, String outputFile, String waterMarkContent) { try { PdfReader reader = new PdfReader(filePath); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile)); //这里的字体设置比较关键,这个设置是支持中文的写法 BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 使用系统字体 PdfGState gs = new PdfGState(); gs.setFillOpacity(0.3f); gs.setStrokeOpacity(0.4f); int total = reader.getNumberOfPages() + 1; JLabel label = new JLabel(); FontMetrics metrics; label.setText(waterMarkContent); metrics = label.getFontMetrics(label.getFont()); int textH = metrics.getHeight(); int textW = metrics.stringWidth(label.getText()); PdfContentByte under; Rectangle pageRect; for (int i = 1; i < total; i++) { pageRect = reader.getPageSizeWithRotation(i); under = stamper.getOverContent(i); under.saveState(); under.setGState(gs); under.beginText(); under.setFontAndSize(base, 22); // 水印文字成30度角倾斜 //你可以随心所欲的改你自己想要的角度 for (int height = interval + textH; height < pageRect.getHeight(); height = height + textH * 10) { for (int width = textW + 20; width < pageRect.getWidth() + textW; width = width + textW * 3) { under.showTextAligned(Element.ALIGN_LEFT, waterMarkContent, width - textW, height, 30); } } // 添加水印文字 under.endText(); } stamper.close(); reader.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } }

测试类

import net.haicoder.watermark.PdfWaterMarkUtil; /** * @author 嗨客网 * @description */ public class TestMain { public static void main(String[] args) { PdfWaterMarkUtil.pdfWaterMark("/Users/haicoder/Documents/code/haicoder/javautil/src/main/java/图片添加水印.pdf", "/Users/haicoder/Documents/code/haicoder/javautil/src/main/java/图片添加水印1.pdf", "你好,嗨客网"); } }

运行效果如下:

09 pdf添加水印后代码结构.png

10 pdf添加水印.png

本书目录

嗨客网顶部