Java给PDF文档添加水印信息

        在word生成pdf后,或者上传pdf文件,用户希望给pdf文档添加水印信息,具体代码如下

  一. 首先pom中需要引入

<!-- PDF水印-->
 <dependency>
     <groupId>com.itextpdf</groupId>
     <artifactId>itextpdf</artifactId>
       <version>5.5.13</version>
 </dependency>
 <!-- 中文字体 -->
 <dependency>
     <groupId>com.itextpdf</groupId>
     <artifactId>itext-asian</artifactId>
     <version>5.2.0</version>
 </dependency>

核心代码如下,写在某个 service 下面

public void signPdf(InputStream is, Supplier<OutputStream> os, List<WaterMarkInfoRequest> signList) {
       PdfStamper stamper = null;
       PdfReader reader = null;
       try {
           reader = new PdfReader(is);
           stamper = new PdfStamper(reader, os.get());
           for (WaterMarkInfoRequest s : signList) {
               TextWaterMarkRequest textWaterMark = s.getTextWaterMark();
               if (textWaterMark != null) {
                   //添加文字
                   BaseFont baseFont;
                   try {
                       baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                   } catch (DocumentException | IOException e) {
                       log.info("pdf签名获取字体信息异常:{}", e.getMessage(), e);
                       throw new BusinessException(IO_ERROR.toErrorInfos("pdf签名获取字体信息异常"));
                   }
                   PdfContentByte content = stamper.getOverContent(textWaterMark.getPageNo());
                   PdfGState gState = new PdfGState();
                   //设置透明度
                   gState.setFillOpacity(textWaterMark.getAlpha());
                   content.setGState(gState);
                   content.beginText();
                   //设置字体
                   content.setFontAndSize(baseFont, textWaterMark.getFontSize());
                   //设置颜色
                   content.setColorFill(new BaseColor(0xFF << 24 | Integer.parseInt(textWaterMark.getFontColor(), 16)));

                   //设置水印内容和位置
                   content.showTextAligned(Element.ALIGN_MIDDLE, textWaterMark.getText(), textWaterMark.getIntervalVertical(), textWaterMark.getIntervalHorizontal(), 0f);
                   content.endText();
               }
               ImageWaterMarkRequest imageWaterMark = s.getImageWaterMark();
               if (imageWaterMark != null) {
                   //添加图片
                   PdfContentByte content = stamper.getOverContent(imageWaterMark.getPageNo());
                   PdfGState gState = new PdfGState();
                   //设置透明度
                   gState.setFillOpacity(imageWaterMark.getAlpha());
                   //image
                   Image image = Image.getInstance(EncryptUtil.base64DecoderToBytes(imageWaterMark.getBase64Str()));
                   image.setAbsolutePosition(imageWaterMark.getPositionX(), imageWaterMark.getPositionY());
                   if (imageWaterMark.getScaleAbsoluteX() != null && imageWaterMark.getScaleAbsoluteY() != null) {
                       image.scaleToFit(imageWaterMark.getScaleAbsoluteX(), imageWaterMark.getScaleAbsoluteY());
                   } else if (imageWaterMark.getScalePercent() != null && imageWaterMark.getScalePercent() > 0) {
                       image.scalePercent(imageWaterMark.getScalePercent());
                   }
                   content.addImage(image);
                   content.stroke();
               }

           }

       } catch (Exception e) {
           e.printStackTrace();
           log.info("添加签名失败:{}", e.getLocalizedMessage(), e);
           WM_WRITE_ERR.throwException();
       } finally {
           if (null != stamper) {
               try {
                   stamper.close();
               } catch (Exception e) {
                   log.info("关闭失败:{}", e.getMessage(), e);
               }
           }
           if (null != reader) {
               reader.close();
           }
       }

   }

用到的实体类

public class ImageWaterMarkRequest{

    @ApiModelProperty(value = "需要添加的页码,默认所有页码都添加")
    private Integer pageNo;
    @ApiModelProperty(value = "水平位置  左下角坐标(0,0)")
    private Integer positionX;
    @ApiModelProperty(value = "垂直位置  左下角坐标(0,0)")
    private Integer positionY;
    @ApiModelProperty(value = "指定图像宽度  ")
    private Integer scaleAbsoluteX;
    @ApiModelProperty(value = "指定图像高度 ")
    private Integer scaleAbsoluteY;
    @ApiModelProperty(value = "缩放比例 与指定尺寸冲突 优先使用指定图像尺寸")
    private Integer scalePercent;
    @ApiModelProperty(value = "图片的二进制数据")
    @NotNull
    private String base64Str;
    @ApiModelProperty(value = "透明度  0--1")
    private Float alpha;

    @ApiModelProperty(value = "透明度  0--1",hidden = true)
    private Float opacity;
    @ApiModelProperty(value = "是否水印打在最顶层  默认true")
    private Boolean isTop;
}
public class WaterMarkInfoRequest {
    @ApiModelProperty(value = "文字水印信息")
    private TextWaterMarkRequest textWaterMark;
    @ApiModelProperty(value = "图片水印信息")
    private ImageWaterMarkRequest imageWaterMark;
}

 方法测试


import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;


public class PdfWaterMarkServiceImplTest {

    public static void main(String[] args) throws Exception {
        InputStream is = Files.newInputStream(Paths.get("/Users/cong/Downloads/a.pdf"));
        OutputStream outputStream = Files.newOutputStream(Paths.get("/Users/cong/Downloads/q-5.pdf"));
        ArrayList<WaterMarkInfoRequest> requests = new ArrayList<>();


        WaterMarkInfoRequest waterMarkInfo = addSign(1);
        WaterMarkInfoRequest waterMarkInfo2 = addSign(1);


        requests.add(waterMarkInfo);
        requests.add(waterMarkInfo2);
        //调用你自己服务的pdf水印方法
        new PdfWaterMarkServiceImpl().signPdf(is, () -> outputStream, requests);
        outputStream.close();
    }

    private static WaterMarkInfoRequest addSign(Integer pageNum) {
        WaterMarkInfoRequest waterMarkInfo = new WaterMarkInfoRequest();

        ImageWaterMarkRequest imageWaterMark = new ImageWaterMarkRequest();
        imageWaterMark.setPageNo(pageNum);
        imageWaterMark.setPositionY(200);
        imageWaterMark.setPositionX(200);
        imageWaterMark.setTop(true);
        imageWaterMark.setAlpha(1.0f);
        imageWaterMark.setBase64Str("图片base64");

        waterMarkInfo.setImageWaterMark(imageWaterMark);

        TextWaterMarkRequest textWaterMark = new TextWaterMarkRequest();
        textWaterMark.setText("我是一个水印");
        textWaterMark.setRotation(0);
        textWaterMark.setAlpha(1.0f);
        textWaterMark.setFontSize(24);
        textWaterMark.setIntervalHorizontal(10);
        textWaterMark.setIntervalVertical(10);
        textWaterMark.setFontColor("800000");
        textWaterMark.setTop(true);
        textWaterMark.setPageNo(pageNum);

        waterMarkInfo.setTextWaterMark(textWaterMark);

        return waterMarkInfo;
    }

}

Java中给PDF添加文本水印,通常需要使用专门的库来处理PDF文件,因为Java标准库本身并不直接支持PDF操作。一个常用的库是iText,它提供了一系列操作PDF文档的工具,包括添加水印的功能。 以下是一个简单的示例代码,展示如何使用iText库为PDF文档添加文本水印: ```java import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.text.BaseColor; import java.io.FileOutputStream; import java.io.FileNotFoundException; public class AddTextWatermark { public static void main(String[] args) { try { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("watermarked.pdf")); document.open(); // 添加水印文本 for (int i = 0; i < 10; i++) { document.add(new Paragraph("这是一个水印", new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 20, com.itextpdf.text.Font.ITALIC, new BaseColor(255, 255, 255, 128)))); } // 关闭文档 document.close(); } catch (DocumentException | FileNotFoundException e) { e.printStackTrace(); } } } ``` 在这段代码中,我们首先创建了一个`Document`对象和一个`PdfWriter`对象,用于写入PDF文件。通过`PdfWriter`将输出文件设置为"watermarked.pdf"。使用`document.open()`打开文档后,我们使用循环添加了10次文本水印,这里的文本是"这是一个水印"。`Font`对象的构造参数定义了字体、大小、样式和透明度。最后关闭文档。 请注意,iText库需要在项目中单独添加依赖。此外,如果需要更复杂的水印样式(如旋转、斜体等),可以通过进一步的设置来实现。
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值