使用iText为PDF加图片水印

  • Maven依赖:


    com.sankuai.mms
    mms-boot
    1.0.3
  • Java代码:

替换watermark_backgroud.png为本地图片即可。

public static void imageWatermark(String inputPath, String outputPath) throws IOException, DocumentException {
 
    PdfReader reader = new PdfReader(inputPath);
    PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(outputPath));
    PdfGState gs1 = new PdfGState();
    gs1.setFillOpacity(0.1f);
 
    Image image = Image.getInstance(IOUtils.toByteArray(new FileInputStream(System.getProperty("user.dir") + "/src/main/webapp/WEB-INF/resources/image/watermark_backgroud.png")));
    int n = reader.getNumberOfPages();
    for(int i = 1; i <= n; i++) {
        PdfContentByte pdfContentByte = stamp.getOverContent(i);
        pdfContentByte.setGState(gs1);
 
        image.setAbsolutePosition(100, 300);
        pdfContentByte.addImage(image);
    }
 
    stamp.close();
    reader.close();
}
  • 效果
使用iText为PDF加图片水印_第1张图片

你可能感兴趣的:(Java)