What are the solutions for adding watermark to PDF using SpringBoot?

Method 1: Use 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 a number of APIs, including the ability to add text watermarks.

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

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

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

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

Then, iterate through all pages in the PDF and add watermarks using PDPageContentStream:

// Traverse all pages in 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);

    //Set font and font size
    contentStream.setFont(PDType1Font.HELVETICA_BOLD, 36);

    //Set transparency
    contentStream.setNonStrokingColor(200, 200, 200);

    //Add text watermark
    contentStream.beginText();
    contentStream.newLineAtOffset(100, 100); //Set the watermark position
    contentStream.showText("Watermark"); // Set watermark content
    contentStream.endText();

    contentStream.close();
}

Finally, the modified PDF file needs to be saved:

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

Complete code
The following is the complete code using PDFBox to add watermark to PDF:

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 {<!-- -->
        //Read the original PDF file
        PDDocument document = PDDocument.load(new File("original.pdf"));

        //Loop through all pages in 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);

            //Set font and font size
            contentStream.setFont(PDType1Font.HELVETICA_BOLD, 36);

            //Set transparency
            contentStream.setNonStrokingColor(200, 200, 200);

            //Add text watermark
            contentStream.beginText();
            contentStream.newLineAtOffset(100, 100); //Set the watermark position
            contentStream.showText("Watermark"); // Set watermark content
            contentStream.endText();

            contentStream.close();
        }

        //Save the modified PDF file
        document.save(new File("output.pdf"));
        document.close();
    }
}

Method 2: Use iText library
iText is a popular Java PDF library that can be used to create, read, modify, and extract PDF content. iText provides a number of 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
Before adding a watermark, the original PDF file needs to be read:

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

Then, iterate through all pages in the PDF and add watermarks using PdfContentByte:

//Get the number of pages in PDF
int pageCount = reader.getNumberOfPages();

//Add watermark
for (int i = 1; i <= pageCount; i + + ) {<!-- -->
    PdfContentByte contentByte = stamper.getUnderContent(i); // or 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, you need to save the modified PDF file and close the file stream:

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

Complete code
The following is the complete code using iText to add watermark to PDF:

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 {<!-- -->
        //Read the original PDF file
        PdfReader reader = new PdfReader("original.pdf");
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("output.pdf"));

        // Get the number of pages in PDF
        int pageCount = reader.getNumberOfPages();

        //Add watermark
        for (int i = 1; i <= pageCount; i + + ) {<!-- -->
            PdfContentByte contentByte = stamper.getUnderContent(i); // or getOverContent()
            contentByte.beginText();
            contentByte.setFontAndSize(BaseFont.createFont(), 36f);
            contentByte.setColorFill(BaseColor.LIGHT_GRAY);
            contentByte.showTextAligned(Element.ALIGN_CENTER, "Watermark", 300, 400, 45);
            contentByte.endText();
        }

        //Save the modified PDF file and close the file stream
        stamper.close();
        reader.close();
    }
}

Method 3: Free Spire.PDF for Java
The following introduces how to use Free Spire.PDF for Java to add watermarks to PDF.

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 dependency of Free Spire.PDF for Java 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 a watermark, the original PDF file needs to be read:

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

Then, iterate through all pages in the PDF and add watermarks using PdfPageBase:

// Traverse all pages in PDF
for (int i = 0; i < pdf.getPages().getCount(); i + + ) {<!-- -->
    PdfPageBase page = pdf.getPages().get(i);

    //Add text watermark
    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 an image watermark is similar to adding a text watermark. You only need to modify the parameters of PdfWatermark to the image path.

//Add image watermark

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

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

import com.spire.pdf.*;

public class FreeSpirePdfWatermark {<!-- -->
    public static void main(String[] args) {<!-- -->
        //Read the original PDF file
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("original.pdf");

        //Loop through all pages in PDF
        for (int i = 0; i < pdf.getPages().getCount(); i + + ) {<!-- -->
            PdfPageBase page = pdf.getPages().get(i);

            //Add text watermark
            PdfWatermark watermark = new PdfWatermark("Watermark");
            watermark.setFont(new PdfFont(PdfFontFamily.Helvetica, 36));
            watermark.setOpacity(0.5f);
            page.getWatermarks().add(watermark);

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

        //Save the modified PDF file
        pdf.saveToFile("output.pdf");
        pdf.close();
    }
}

Method 4: 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 Aspose.PDF for Java API in a Spring Boot application to set a PDF watermark.

Add text watermark

@PostMapping("/addTextWatermark")
public ResponseEntity<byte[]> addTextWatermark(@RequestParam("file") MultipartFile file) throws IOException {<!-- -->
    //Load PDF file
    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);

    //Save PDF file
    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 {<!-- -->
    //Load PDF file
    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);

    //Save PDF file
    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.

Complete 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 {<!-- -->
        //Load PDF file
        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);

        //Save PDF file
        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 {<!-- -->
        //Load PDF file
        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);

        //Save PDF file
        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 watermarks and image watermarks respectively. Pass the PDF file via the file parameter in the request.

Here’s how to use Postman to test the API of a Spring Boot application.

Download and install Postman.
Open Postman and select the POST request method.
Enter http://localhost:8080/api/pdf/addTextWatermark in the URL address bar.
Set the Content-Type in the Headers tab to multipart/form-data.
Select the form-data type in the Body tab, then set the key to file and the value to select a local PDF file.
Click the Send button to send the request and wait for the response.
The processing result will be returned in the Body of the response, and you can also choose to download it with the browser or save it to the local disk.

The above is how to add PDF watermark using Aspose.PDF for Java library combined with Spring Boot.