pdf添加水印,vue+java

1、vue

自定义上传行为:

    <el-upload
        :file-list="fileList"
        :http-request="updateFile"
        :limit="1"
        :on-error="errorFile"
        action=""
        class="upload-demo"
        multiple>
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>

除了上传文件外,还需要上传水印内容,所以自定义上传方法,也方便后期拓展水印需求。

     const config = {
        method: 'post',
        url: '/pdfWaterMark',
        headers: {
          'Accept': '*/*',
          'Content-Type': 'multipart/form-data',
        },
        responseType: 'blob',
        data: data
      };

采用表单形式提交请求,以二进制接受响应,这是重点,亦可采用其他方式处理接口响应,然后将流处理为文件并下载即可。

2、java

接收上传的pdf文件,通过指定的水印文本对其进行修改,并将最终生成的pdf内容以字节数组的形式返回。

@PostMapping("/pdfWaterMark")
    public byte[] pdfWaterMark(MultipartFile file, String waterText) throws IOException {
        System.out.println(waterText);
        byte[] pdfFileBytes = file.getBytes();
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            PdfReader reader = new PdfReader(pdfFileBytes);
            PdfStamper stamper = new PdfStamper(reader, outputStream);
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", true);
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.2f);
            gs.setStrokeOpacity(0.3f);
            int totalPage = reader.getNumberOfPages() + 1;
            for (int i = 1; i < totalPage; i++) {
                PdfContentByte content = stamper.getOverContent(i);
                content.beginText();
                content.setGState(gs);
                content.setFontAndSize(baseFont, 10);
                for (int j = 0; j < 3; j++) {
                    for (int k = 0; k < 4; k++) {
                        int x = 150 + (j * 130);
                        int y = 100 + (k * 230);
                        content.showTextAligned(PdfContentByte.ALIGN_CENTER, waterText, x, y, 45);
                    }
                }
                content.endText();
            }
            stamper.close();
            reader.close();
            return outputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

可以自己设置字体,大小,透明度,页数等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值