1
.依賴
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
2.水印圖片在項目中的位置
3.代碼實現
import com.itextpdf.text.Image;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileOutputStream;
import java.io.IOException;
/***
* PDF水印工具類
*/
public class PDFWatermarkUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(PDFWatermarkUtil.class);
/***
* 執行添加圖片水印
* @param inputFilePath 原始文件
* @param outputFilePath 添加水印文件
* @param watermarkPath 水印圖片
*/
public static boolean addWatermark(String inputFilePath, String outputFilePath, String watermarkPath) {
FileOutputStream fileOutputStream = null;
try {
// 待加水印的文件
PdfReader pdfReader = new PdfReader(inputFilePath);
fileOutputStream = new FileOutputStream(outputFilePath);
// 加完水印的文件
PdfStamper pdfStamper = new PdfStamper(pdfReader, fileOutputStream);
int total = pdfReader.getNumberOfPages() + 1;
//設置透明度
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.3f);
Image image = Image.getInstance(watermarkPath);
//循環對每頁插入水印
for (int i = 1; i < total; i++) {
PdfContentByte pdfContentByte = pdfStamper.getOverContent(i);
pdfContentByte.setGState(gs);
image.setAbsolutePosition(0, 0);
pdfContentByte.addImage(image);
}
pdfStamper.close();
pdfReader.close();
} catch (Exception e) {
LOGGER.error("executeWatermark exception", e);
return false;
}finally {
try {
if(fileOutputStream != null){
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (IOException e) {
LOGGER.error("fileOutputStream close exception", e);
}
}
return true;
}
}