PDF文档加水印
程序员文章站
2024-03-20 22:32:22
...
添加依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.2</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
工具类
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
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;
public class PdfUtils {
//mark为水印文字
public static void addWatermark(InputStream is, OutputStream os, String mark, boolean flag)
throws Exception {
PdfReader pdfReader = new PdfReader(is);
PdfStamper pdfStamper = new PdfStamper(pdfReader, os);
toAddWatermark(pdfStamper, mark, flag);
pdfStamper.close();
}
private static void toAddWatermark(PdfStamper pdfStamper, String waterMarkName, boolean flag) {
PdfContentByte content = null;
BaseFont base = null;
Rectangle pageRect = null;
PdfGState gs = new PdfGState();
try {
// 设置字体
base = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (base == null || pdfStamper == null) {
return;
}
// 设置透明度为0.2
gs.setFillOpacity(0.2f);
gs.setStrokeOpacity(0.2f);
int toPage = pdfStamper.getReader().getNumberOfPages();
for (int i = 1; i <= toPage; i++) {
pageRect = pdfStamper.getReader().getPageSizeWithRotation(i);
// 计算水印X,Y坐标
float x = pageRect.getWidth();
float y = pageRect.getHeight();
// 获得PDF最顶层
content = pdfStamper.getOverContent(i);
content.saveState();
// set Transparency
content.setGState(gs);
content.beginText();
content.setColorFill(BaseColor.GRAY);
content.setFontAndSize(base, 24);
if (flag) {
// 水印文字成45度角倾斜
for (int z = 0; z < 3; z++) {
content.showTextAligned(Element.ALIGN_CENTER,
waterMarkName + " " + waterMarkName, x * z / 3f,
y * (1 - z / 3f), 45);
}
} else {
// 水印文字成45度角倾斜
for (int z = 0; z < 5; z++) {
content.showTextAligned(Element.ALIGN_CENTER,
waterMarkName + " " + waterMarkName, x * z / 5f,
y * (1 - z / 5f), 45);
}
}
content.endText();
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
content = null;
base = null;
pageRect = null;
}
}
}
推荐阅读
-
PDF文档加水印
-
Itext5库的对PDF文件的基本操作(一)---新建文档,设置文档属性,设置文档密码
-
如何基于DevExpress实现对PDF等文档预览及操作处理 DevExpressPDF文档处理
-
java实现图片上加文字水印(SpringMVC + Jsp)
-
如何使用Adobe Reader复制PDF文档上的文字 Adobe ReaderPDF阅读器
-
java实现图片上加文字水印(SpringMVC + Jsp)
-
asp.net下用Aspose.Words for .NET动态生成word文档中的图片或水印的方法
-
asp.net下用Aspose.Words for .NET动态生成word文档中的图片或水印的方法
-
利用java批量给pdf加水印的方法示例
-
JAVA读取PDF、WORD文档实例代码