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;
}
}
可以自己设置字体,大小,透明度,页数等。