首先给PDF加上水印需要倒入两个依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.3</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
代码:
File file = new File(需要加水印的PDF路径);
String saveFilePaths= 加上水印保存的路径;
File filetwo = new File(saveFilePaths);
try {
if (!filetwo.exists()) {
//因为两个文件路径不能相同,吧原来的文件拷贝至新的文件夹下
copyFileUsingJava7Files(file, filetwo);
}
} catch (IOException e) {
e.printStackTrace();
}
// 要输出的pdf文件
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 将pdf文件先加水印然后输出
try {
setWatermark(bos, saveFilePaths,title);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(filetwo.getName());
//生成文件之后删除拷贝文件,以免占用内存
filetwo.delete();
}
if (file.exists()) {
byte[] data;
try {
FileInputStream input = new FileInputStream(file);
data = new byte[input.available()];
int n = input.read(data);
response.getOutputStream().write(data);
input.close();
System.out.println("preview pdf:" + n);
} catch (Exception e) {
e.printStackTrace();
}
}
两个实现方法:
//文件拷贝
private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
java.nio.file.Files.copy(source.toPath(), dest.toPath());
}
//水印生成
public static void setWatermark(BufferedOutputStream bos, String input,String title) throws Exception,
IOException {
PdfReader reader = new PdfReader(input);
PdfStamper stamper = new PdfStamper(reader, bos);
int total = reader.getNumberOfPages() + 1;
PdfContentByte content;
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED);
PdfGState gs = new PdfGState();
for (int i = 1; i < total; i++) {
content = stamper.getOverContent(i);// 在内容上方加水印
//content = stamper.getUnderContent(i);//在内容下方加水印
gs.setFillOpacity(0.2f);
// content.setGState(gs);
content.beginText();
content.setColorFill(new BaseColor(148,148,148));
content.setFontAndSize(base, 50);
content.setTextMatrix(70, 200);
content.showTextAligned(Element.ALIGN_CENTER, title, 300,350, 55);
/*content.setColorFill(Color.);*/
content.setFontAndSize(base, 8);
content.endText();
}
try {
stamper.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
通过以上的方法可以实现pdf文字水印