添加依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
<scope>compile</scope>
</dependency>
添加字体simsun.ttf
到resources/fonts
目录下
代码
import cn.hutool.core.io.IoUtil;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.*;
private void addPdfWatermark(InputStream inputStream, OutputStream outputStream, String watermark) throws IOException, DocumentException, FontFormatException {
PdfReader pdfReader = new PdfReader(inputStream);
PdfStamper stamper = new PdfStamper(pdfReader, outputStream);
int total = pdfReader.getNumberOfPages();
PdfContentByte content = null;
byte[] fontBytes = IoUtil.readBytes(new ClassPathResource("fonts/simsun.ttf").getInputStream());
PdfGState gs = new PdfGState();
for (int i = 1; i <= total; i++) {
content = stamper.getOverContent(i);
gs.setFillOpacity(0.3f);
content.setGState(gs);
content.beginText();
content.setColorFill(BaseColor.RED);
content.setFontAndSize(BaseFont.createFont("simsun.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED, true, fontBytes, null), 50F);
content.showTextAligned(Element.ALIGN_CENTER, watermark, 300F, 400F, 45F);
content.endText();
}
stamper.close();
pdfReader.close();
}