依赖包
compile(‘com.itextpdf:itextpdf:5.5.3’)
import java.awt.FontMetrics;
import java.io.*;
import javax.swing.JLabel;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import jodd.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class PdfWatermarkUtil {
/**
* 给pdf文件加水印
* @param inputStream
* @param waterMarkName
* @return
* @throws Exception
*/
public static InputStream waterMark(InputStream inputStream,String waterMarkName) throws Exception{
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PdfReader reader = new PdfReader(inputStream);
PdfStamper stamper = new PdfStamper(reader,bos);
BaseFont base = BaseFont.createFont();
Rectangle pageRect;
PdfGState gs = new PdfGState();
//设置透明度
gs.setFillOpacity(0.1f);
gs.setStrokeOpacity(0.1f);
int total = reader.getNumberOfPages() + 1;
JLabel label = new JLabel();
FontMetrics metrics;
int textH;
int textW;
label.setText(waterMarkName);
metrics = label.getFontMetrics(label.getFont());
textH = metrics.getHeight();
textW = metrics.stringWidth(label.getText());
PdfContentByte under;
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, 14);
//设置水印颜色
under.setColorFill(BaseColor.BLACK);
// 水印文字成30度角倾斜
for (int height = textH; height < pageRect.getHeight(); height = height + textH * 4) {
for (int width = textW; width < pageRect.getWidth() + textW; width = width + textW + textW/5 ) {
under.showTextAligned(Element.ALIGN_LEFT ,waterMarkName, width - textW, height - textH,
30);
}
}
// 添加水印文字
under.endText();
}
stamper.close();
reader.close();
inputStream.close();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bos.toByteArray());
return byteArrayInputStream;
} catch (Exception e) {
e.printStackTrace();
log.error("图片添加水印异常"+e.getMessage(),e);
throw e;
}
}
}