81,122
社区成员




// 读取源PDF文件
PdfReader reader = new PdfReader(pdfPath);
int n = reader.getNumberOfPages();
// 复制文件
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(newPdfPath));
int i = 0;
PdfContentByte under;
PdfGState gs = new PdfGState();
// 配置信息内容
String textContent = String.valueOf(configMap.get("textContent"));
BLOB imageContent = (BLOB) configMap.get("imageContent");
String angle = String.valueOf(configMap.get("angle"));
if ("".equals(angle) || "null".equals(angle)) {
angle = "0";
}
String diaphaneity = String.valueOf(configMap.get("diaphaneity"));
String position = String.valueOf(configMap.get("position"));
// 转换透明度(默认为50%)
float diaphaneityF = 0.5f;
if (!"".equals(diaphaneity) && !"null".equals(diaphaneity)) {
diaphaneityF = (100f - Float.parseFloat(diaphaneity)) / 100;
}
// 添加水印
// 水印字体
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
while (i < n) {
i++;
under = stamp.getUnderContent(i);
Rectangle pageRect = stamp.getReader().getPageSizeWithRotation(i);
// 设置透明度
gs.setFillOpacity(diaphaneityF);
gs.setStrokeOpacity(diaphaneityF);
under.setGState(gs);
// 开始
under.beginText();
String align = "center";// 文字对齐方式
// 设置位置
float x = 0;
float y = 0;
if ("1".equals(position)) { // 左上
x = 10;
y = pageRect.getHeight() - 40;
under.setFontAndSize(bf, 32); // 文字大小
align = "left";
} else if ("2".equals(position)) { // 中上
x = pageRect.getWidth() / 2;
y = pageRect.getHeight() - 40;
under.setFontAndSize(bf, 32);// 文字大小
align = "center";
} else if ("3".equals(position)) { // 右上
x = pageRect.getWidth() - 10;
y = pageRect.getHeight() - 40;
under.setFontAndSize(bf, 32);// 文字大小
align = "right";
} else if ("4".equals(position)) { // 左中
x = 10;
y = pageRect.getHeight() / 2;
under.setFontAndSize(bf, 32);// 文字大小
align = "left";
} else if ("5".equals(position)) { // 中中
x = pageRect.getWidth() / 2;
y = pageRect.getHeight() / 2;
under.setFontAndSize(bf, 50);// 文字大小
align = "center";
} else if ("6".equals(position)) { // 右中
x = pageRect.getWidth() - 10;
y = pageRect.getHeight() / 2;
under.setFontAndSize(bf, 32);// 文字大小
align = "right";
} else if ("7".equals(position)) { // 左下
x = 10;
y = 10;
under.setFontAndSize(bf, 32);// 文字大小
align = "left";
} else if ("8".equals(position)) { // 中下
x = pageRect.getWidth() / 2;
y = 10;
under.setFontAndSize(bf, 32);// 文字大小
align = "center";
} else if ("9".equals(position)) { // 右下
x = pageRect.getWidth() - 10;
y = 10;
under.setFontAndSize(bf, 32);// 文字大小
align = "right";
}
under.setRGBColorFill(40, 125, 231);// 文字颜色
if ("left".equals(align)) {
under.showTextAligned(Element.ALIGN_LEFT, textContent, x, y, Integer.parseInt(angle));// 设置文字水印位置方向
} else if ("center".equals(align)) {
under.showTextAligned(Element.ALIGN_CENTER, textContent, x, y, Integer.parseInt(angle));// 设置文字水印位置方向
} else if ("right".equals(align)) {
under.showTextAligned(Element.ALIGN_RIGHT, textContent, x, y, Integer.parseInt(angle));// 设置文字水印位置方向
}
// 结束
under.endText();
stamp.close();