SpringBoot 实现 PDF 添加水印

1.使用 Apache PDFBox 库

1.1添加 PDFBox 依赖

java 复制代码
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.24</version>
</dependency>

1.2添加水印

PDDocument document = PDDocument.load(new File("原始.pdf"));

java 复制代码
// 遍历 PDF 中的所有页面
for (int i = 0; i < document.getNumberOfPages(); i++) {
    PDPage page = document.getPage(i);
    PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true);

    // 设置字体和字号
    contentStream.setFont(PDType1Font.HELVETICA_BOLD, 36);

    // 设置透明度
    contentStream.setNonStrokingColor(200, 200, 200);

    // 添加文本水印
    contentStream.beginText();
    contentStream.newLineAtOffset(100, 100); // 设置水印位置
    contentStream.showText("水印"); // 设置水印内容
    contentStream.endText();

    contentStream.close();
}

document.save(new File("output.pdf"));

document.close();

2.使用 iText 库

2.1添加 iText 依赖

java 复制代码
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13</version>
</dependency>
java 复制代码
  // 读取原始 PDF 文件
        PdfReader reader = new PdfReader("原始.pdf");
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("输出.pdf"));

        // 获取 PDF 中的页数
        int pageCount = reader.getNumberOfPages();

        // 添加水印
        for (int i = 1; i <= pageCount; i++) {
            PdfContentByte contentByte = stamper.getUnderContent(i); // 或者 getOverContent()
            contentByte.beginText();
            contentByte.setFontAndSize(BaseFont.createFont(), 36f);
            contentByte.setColorFill(BaseColor.LIGHT_GRAY);
            contentByte.showTextAligned(Element.ALIGN_CENTER, "水印", 300, 400, 45);
            contentByte.endText();
        }

        // 保存修改后的 PDF 文件并关闭文件流
        stamper.close();
        reader.close();

3.Free Spire.PDF for Java

3.1. 添加 Free Spire.PDF for Java 依赖

<dependency>

<groupId>e-iceblue</groupId>

<artifactId>free-spire-pdf-for-java</artifactId>

<version>1.9.6</version>

</dependency>

java 复制代码
 // 读取原始 PDF 文件
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("原始.pdf");

        // 遍历 PDF 中的所有页面
        for (int i = 0; i < pdf.getPages().getCount(); i++) {
            PdfPageBase page = pdf.getPages().get(i);

            // 添加文本水印
            PdfWatermark watermark = new PdfWatermark("水印");
            watermark.setFont(new PdfFont(PdfFontFamily.Helvetica, 36));
            watermark.setOpacity(0.5f);
            page.getWatermarks().add(watermark);

            // 添加图片水印
            // PdfWatermark watermark = new PdfWatermark("水印.png");
            // watermark.setOpacity(0.5f);
            // page.getWatermarks().add(watermark);
        }

        // 保存修改后的 PDF 文件
        pdf.saveToFile("输出.pdf");
        pdf.close();

4.Aspose.PDF for Java

4.1 依赖

<dependency>

<groupId>com.aspose</groupId>

<artifactId>aspose-pdf</artifactId>

<version>21.4</version>

</dependency>

java 复制代码
@RestController
@RequestMapping("/api/pdf")
public class PdfController {
    @PostMapping("/addTextWatermark")
    public ResponseEntity<byte[]> addTextWatermark(@RequestParam("file") MultipartFile file) throws IOException {
        // 加载 PDF 文件
        Document pdfDocument = new Document(file.getInputStream());
        TextStamp textStamp = new TextStamp("水印");
        textStamp.setWordWrap(true);
        textStamp.setVerticalAlignment(VerticalAlignment.Center);
        textStamp.setHorizontalAlignment(HorizontalAlignment.Center);
        pdfDocument.getPages().get_Item(1).addStamp(textStamp);

        // 保存 PDF 文件
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        pdfDocument.save(outputStream);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"watermarked.pdf\"")
                .contentType(MediaType.APPLICATION_PDF)
                .body(outputStream.toByteArray());
    }

    @PostMapping("/addImageWatermark")
    public ResponseEntity<byte[]> addImageWatermark(@RequestParam("file") MultipartFile file) throws IOException {
        // 加载 PDF 文件
        Document pdfDocument = new Document(file.getInputStream());
        ImageStamp imageStamp = new ImageStamp("水印图片.png");
        imageStamp.setWidth(100);
        imageStamp.setHeight(100);
        imageStamp.setVerticalAlignment(VerticalAlignment.Center);
        imageStamp.setHorizontalAlignment(HorizontalAlignment.Center);
        pdfDocument.getPages().get_Item(1).addStamp(imageStamp);

        // 保存 PDF 文件
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        pdfDocument.save(outputStream);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"watermarked.pdf\"")
                .contentType(MediaType.APPLICATION_PDF)
                .body(outputStream.toByteArray());
    }
}
相关推荐
程序员爱钓鱼几秒前
Go 并发编程基础:select 多路复用
后端·google·go
坚持学习永不言弃几秒前
简单工厂、工厂方法模式、抽象工厂模式
后端
猩猩程序员4 分钟前
别乱用二分查找!这些前提条件你都搞清楚了吗?
后端
Livingbody17 分钟前
通过huggingface学习【自动语音识别(Automatic Speech Recognition, ASR)】
后端
~plus~21 分钟前
Harmony核心:动态方法修补与.NET游戏Mod开发
开发语言·jvm·经验分享·后端·程序人生·c#
~plus~30 分钟前
WPF八大法则:告别模态窗口卡顿
开发语言·经验分享·后端·程序人生·c#
Livingbody35 分钟前
Transformers Pipeline 入门之【任务列表】
后端
[email protected]42 分钟前
ASP.NET Core SignalR - 部分客户端消息发送
后端·asp.net·.netcore
寻月隐君42 分钟前
深入解析 Rust 的面向对象编程:特性、实现与设计模式
后端·rust·github
追逐时光者1 小时前
免费且全面的C#/.NET/.NET Core面试宝典,阅读量突破40万+了!
后端·.net