SpringBoot implements PDF watermarking scheme

Introduction

PDF (Portable Document Format) is a popular file format that can be viewed and printed on multiple operating systems and applications. In some cases, we need to add watermark to PDF file to make it more recognizable or to protect its copyright. This article will introduce how to use Spring Boot to realize the way of adding watermark to PDF.

Method 1: Use the Apache PDFBox library

PDFBox is a popular, free library written in Java that can be used to create, modify, and extract PDF content. PDFBox provides many APIs, including the ability to add text watermarks.

Add PDFBox dependency

First, add the PDFBox dependency in the pom.xml file:

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.24</version>
</dependency>

add watermark

Before adding the watermark, the original PDF file needs to be read:

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

Then, iterate over all pages in the PDF and add the watermark using PDPageContentStream:

// 遍历 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("Watermark"); // 设置水印内容
    contentStream.endText();

    contentStream.close();
}

Finally, the modified PDF file needs to be saved:

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

full code

The following is the complete code for adding watermark to PDF using PDFBox:

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

import java.io.File;
import java.io.IOException;

public class PdfBoxWatermark {
    
    
    public static void main(String[] args) throws IOException {
    
    
        // 读取原始 PDF 文件
        PDDocument document = PDDocument.load(new File("original.pdf"));

        // 遍历 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("Watermark"); // 设置水印内容
            contentStream.endText();

            contentStream.close();
        }

        // 保存修改后的 PDF 文件
        document.save(new File("output.pdf"));
        document.close();
    }
}

Method 2: Use the iText library

iText is a popular Java PDF library that can be used to create, read, modify and extract PDF content. iText provides many APIs, including the ability to add text watermarks.

Add iText dependency

Add iText dependency in the pom.xml file:

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13</version>
</dependency>

add watermark

PdfReader reader = new PdfReader("original.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("output.pdf"));

Then, iterate over all pages in the PDF and add the watermark using PdfContentByte:

// 获取 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, "Watermark", 300, 400, 45);
    contentByte.endText();
}

Finally, the modified PDF file needs to be saved and the file stream closed:

stamper.close();
reader.close();

full code

The following is the complete code for adding watermark to PDF using iText:

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import java.io.FileOutputStream;
import java.io.IOException;

public class ItextWatermark {
    
    
    public static void main(String[] args) throws IOException, DocumentException {
    
    
        // 读取原始 PDF 文件
        PdfReader reader = new PdfReader("original.pdf");
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("output.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, "Watermark", 300, 400, 45);
            contentByte.endText();
        }

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

Free Spire.PDF for Java

The following introduces how to add watermark to PDF using Free Spire.PDF for Java.

Free Spire.PDF for Java is a free Java PDF library that provides an easy-to-use API for creating, reading, modifying and extracting PDF content. Free Spire.PDF for Java also supports adding text watermarks and image watermarks.

Add Free Spire.PDF for Java dependency

First, add the Free Spire.PDF for Java dependency in the pom.xml file:

<dependency>
    <groupId>e-iceblue</groupId>
    <artifactId>free-spire-pdf-for-java</artifactId>
    <version>1.9.6</version>
</dependency>

Add text watermark

Before adding the watermark, the original PDF file needs to be read:

PdfDocument pdf = new PdfDocument();
pdf.loadFromFile("original.pdf");

Then, iterate over all pages in the PDF and add the watermark using PdfPageBase:

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

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

Finally, the modified PDF file needs to be saved:

pdf.saveToFile("output.pdf");
pdf.close();

Add image watermark

Adding a picture watermark is similar to adding a text watermark, you only need to modify the parameter of PdfWatermark to the picture path

PdfWatermark watermark = new PdfWatermark("watermark.png");
watermark.setOpacity(0.5f);
page.getWatermarks().add(watermark);

full code

The following is the complete code for adding watermark to PDF using Free Spire.PDF for Java:

import com.spire.pdf.*;

public class FreeSpirePdfWatermark {
    
    
    public static void main(String[] args) {
    
    
        // 读取原始 PDF 文件
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("original.pdf");

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

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

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

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

Aspose.PDF for Java

Aspose.PDF for Java is a powerful PDF processing library that provides the function of adding watermarks. The way to add PDF watermark using Aspose.PDF for Java library in combination with Spring Boot is as follows:
First, add the dependency of Aspose.PDF for Java in the pom.xml file:

<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-pdf</artifactId>
    <version>21.4</version>
</dependency>

Call the API of Aspose.PDF for Java in the Spring Boot application to set the PDF watermark.

Add text watermark

@PostMapping("/addTextWatermark")
public ResponseEntity<byte[]> addTextWatermark(@RequestParam("file") MultipartFile file) throws IOException {
    
    
    // 加载 PDF 文件
    Document pdfDocument = new Document(file.getInputStream());
    TextStamp textStamp = new TextStamp("Watermark");
    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());
}

Add image watermark

@PostMapping("/addImageWatermark")
public ResponseEntity<byte[]> addImageWatermark(@RequestParam("file") MultipartFile file) throws IOException {
    
    
    // 加载 PDF 文件
    Document pdfDocument = new Document(file.getInputStream());
    ImageStamp imageStamp = new ImageStamp("watermark.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());
}

Note that the file name, width, height and other parameters in the above code need to be adjusted according to the actual situation.

full code

The complete Spring Boot controller class code is as follows:

import com.aspose.pdf.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

@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("Watermark");
        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("watermark.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());
    }
}

Two RESTful APIs are used here: /addTextWatermark and /addImageWatermark, which are used to add text watermark and image watermark respectively. Pass the PDF file through the file parameter in the request.

in conclusion

This article introduces several ways to add watermark to PDF using Spring Boot, namely using Apache PDFBox library, iText library and Ghostscript command line, etc. Which method to choose can be decided according to project requirements and personal preferences. No matter which way you use, you need to pay attention to protecting the original PDF file, and don't directly modify the original file under unnecessary circumstances. Welcome to like and collect.

Guess you like

Origin blog.csdn.net/houxian1103/article/details/131547988