springboot如何给pdf文件添加上指定的水印
时间: 2024-09-18 14:07:32 浏览: 61
Spring Boot Messaging 无水印pdf
在Spring Boot应用中添加PDF水印通常需要第三方库的支持,例如Apache PDFBox或者iText等。以下是一个简单的步骤概述:
1. 添加依赖:首先,在你的`pom.xml`文件中添加PDF处理库的依赖。例如,如果你选择Apache PDFBox,可以添加以下内容:
```xml
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>最新版本号</version>
</dependency>
```
2. 创建工具类:创建一个工具类,比如`WatermarkService`,用于生成和添加水印:
```java
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
public class WatermarkService {
private static final String WATERMARK_TEXT = "your watermark text"; // 水印文字
public void addWatermarkToPdf(PDDocument document) {
try (PDFTextStripper stripper = new PDFTextStripper()) {
String extractedText = stripper.getText(document);
// 添加水印到每一页
for (int i = 0; i < document.getNumberOfPages(); i++) {
PDPage page = document.getPage(i);
float x = page.getImageBoundingBox().getWidth() - 100; // 可调整位置
float y = page.getImageBoundingBox().getHeight() - 50; // 可调整高度
PDXObjectForm form = PDXObjectForm.create(document, "/Resources/Forms/Form1");
form.addTemplate(page);
form.setNon RotatedBox(new Rectangle(x, y, 100, 50)); // 水印大小
form.beginFormAppearance();
form.showTextAt(0, 0, WATERMARK_TEXT);
form.endFormAppearance();
page.setForm(form);
}
} catch (IOException e) {
throw new RuntimeException("Failed to add watermark", e);
}
}
}
```
3. 使用服务:在你需要操作PDF的地方,如Controller,注入这个服务并调用方法:
```java
@Autowired
private WatermarkService watermarkService;
@GetMapping("/generate-watermarked-pdf")
public ResponseEntity<byte[]> generateWatermarkedPdf(@RequestParam("file") MultipartFile file) {
try {
byte[] originalContent = file.getBytes();
PDDocument document = PDDocument.load(originalContent);
watermarkService.addWatermarkToPdf(document);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
document.save(outputStream);
document.close();
return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM).body(outputStream.toByteArray());
} catch (Exception e) {
return ResponseEntity.badRequest().body("Error adding watermark");
}
}
```
阅读全文