Add Watermark to PDF with Spring Boot

Way 1: using Apache PDFBox library

The Apache PDFBox® library is an open source Java tool for working with PDF documents. This project allows creation of new PDF documents, manipulation of existing documents and the ability to extract content from documents. 

PDFBox provides a number of APIs, including the ability to add text watermarks.

Recommend an open source free Spring Boot practice project

 https://github.com/javastacks/spring-boot-best-practice

Add PDFBox dependencies to the pom.xml file

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

Read the original PDF file
PDDocument document = PDDocument.load(new File("original.pdf"));
Adding a Watermark with PDPageContentStream
// 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(); }
Save the modified PDF file
document.save(new File("output.pdf")); document.close();
Full Code
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 { // PDDocument document = PDDocument.load(new File("original.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(); } // document.save(new File("output.pdf")); document.close(); } }
Way 2: Use the iText library
Apache iText is an open-source Java library that supports the development and conversion of PDF documents. 

Add the 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"));

Iterate through all the pages in the PDF, using PdfContentByte 

// 
int pageCount = reader.getNumberOfPages();

// 
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();

Full Code

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

        // 
        int pageCount = reader.getNumberOfPages();

        // 
        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();
        }

        // 
        stamper.close();
        reader.close();
    }
}

Way 3: Using the Ghostscript Command Line

Ghostscript is a suite of software based on an interpreter for Adobe Systems' PostScript and Portable Document Format (PDF) page description languages.

Ghostscript

Download and install Ghostscript:

https://www.ghostscript.com/releases/index.html

Add Watermark

Using Ghostscript commands in the terminal

gs -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=output.pdf -c "newpath /Helvetica-Bold findfont 36 scalefont setfont 0.5 setgray 200 200 moveto (Watermark) show showpage" original.pdf

Way 4:Free Spire.PDF for Java

Free Spire.PDF for Java is a 100% free PDF API that enables Java applications to read, write and save PDF documents without using Adobe Acrobat.

Add Free Spire.PDF for Java dependency in pom.xml 

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

Adding a text watermark

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

Iterate over all pages in a PDF and add a watermark usingPdfPageBase 

// 
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);
}


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

Add image watermark

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

Full Code

import com.spire.pdf.*;

public class FreeSpirePdfWatermark {
    public static void main(String[] args) {
        // 
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("original.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.saveToFile("output.pdf");
        pdf.close();
    }
}

Way 5:Aspose.PDF for Java

Aspose.PDF for Java is a PDF document creation component that enables your Java applications to read, write and manipulate PDF documents without using Adobe Acrobat.

https://github.com/aspose-pdf/Aspose.PDF-for-Java

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

Adding a text watermark

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

    // 
    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 {
    // 
    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);

    // 
    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());
}

Full Code

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 {
        // 
        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);

        // 
        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 {
        // 
        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);

        // 
        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());
    }
}

Postman is an API platform for building and using APIs. Postman simplifies each step of the API lifecycle and streamlines collaboration so you can create better APIs—faster.

https://learning.postman.com/docs/introduction/overview/
Post a Comment (0)
Previous Post Next Post