java实现pdf文件添加水印,下载到浏览器
添加itextpdf依赖
<dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.8</version>
</dependency>
文件下载到浏览器和指定路径
根据需求,不需要指定路径可以删除对应的输出流
public void addPDFImageWaterMark(MultipartFile srcFile, MultipartFile imagePath, HttpServletResponse response) {String fileName = "test.pdf";PdfReader reader = null;PdfStamper stamper = null;FileInputStream fileInputStream = null;//这个输出流要放入PdfStamper构造方法中,这里也会下载一个文件,不需要的话可以在finally中删除FileOutputStream fileOutputStream = null;//下载到你指定的路径,try里面new的路径,不需要下载到指定路径可以删除FileOutputStream fos = null;// 设置响应头,指定内容类型和文件名,准备下载到浏览器,下载到指定位置,不需要下载到浏览器可以删除这个输出流ServletOutputStream outputStream = null;response.setContentType("application/pdf");response.setHeader("Content-Disposition", "attachment; filename=" + srcFile.getOriginalFilename());try {outputStream = response.getOutputStream();//如果是路径的话可以使用另一个构造方法reader = new PdfReader(srcPath);reader = new PdfReader(srcFile.getBytes());fileOutputStream = new FileOutputStream(fileName);stamper = new PdfStamper(reader, fileOutputStream);//加载图片//如果是路径的话可以使用另一个构造方法Image image =Image.getInstance(imagePath);Image image = Image.getInstance(imagePath.getBytes());//将图片控制大小,适配这个大小image.scaleToFit(200, 100);PdfGState gs = new PdfGState();//gs.setFillOpacity(0.2f);//图片水印透明度//gs.setStrokeOpacity(0.4f);//设置笔触字体不透明度PdfContentByte content = null;int total = reader.getNumberOfPages();//pdf文件页数for (int i = 0; i < total; i++) {float x = reader.getPageSize(i + 1).getWidth();//页宽度float y = reader.getPageSize(i + 1).getHeight();//页高度content = stamper.getOverContent(i + 1);content.setGState(gs);content.beginText();//开始写入//每页7行,一行3个for (int j=0; j<3; j++) {for (int k=0; k<7; k++) {//setAbsolutePosition 方法的参数(输出水印X轴位置,Y轴位置)image.setAbsolutePosition(x/3*j-30, y/7*k-20);content.addImage(image);}}content.endText();//结束写入}//要先关闭流才能将生成的文件写到指定地方!!!stamper.close();reader.close();//指定这个文件(这里我用的相对路径)fileInputStream = new FileInputStream(fileName);//创建输出流,下载到指定路径fos = new FileOutputStream("test1.pdf");byte[] buffer = new byte[1024];int bytesRead = 0;while ((bytesRead = fileInputStream.read(buffer)) != -1) {// 浏览器下载outputStream.write(buffer, 0, bytesRead);//下载到指定路径fos.write(buffer, 0, bytesRead);}} catch (Exception e) {e.printStackTrace();} finally {try {//关闭流if (stamper != null) {stamper.close();}if (reader != null) {reader.close();}if (fos != null) {fos.close();}if (fileInputStream != null) {fileInputStream.close();}if (fileOutputStream != null) {fileOutputStream.close();}if (outputStream != null) {outputStream.close();}} catch (Exception e) {e.printStackTrace();}}
}
效果如下:代码中的相对路径在src平级目录下,test.pdf是PdfStamper里面fileOutputStream生成的,test1.pdf是fos生成的
浏览器下载的如下:
生成的pdf内容如下(红框里面是pdf原来的内容,可以自己调整代码中注释掉的设置水印透明度来调整)
提供的前端代码自行测试
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body><h2>测试PDF添加水印</h2><form method="post" action="http://localhost:8080/addPDFImageWaterMark" enctype="multipart/form-data"><label for="srcFile">选择PDF文件:</label><input type="file" name="srcFile" id="srcFile" accept=".pdf" required><br><label for="imagePath">选择水印图片:</label><input type="file" name="imagePath" id="imagePath" accept=".jpg, .png" required><br><button type="submit">添加水印并下载</button></form></body>
</html>