How to Add Watermarks to PDF Files Using Spring Boot and Java Libraries
This article demonstrates multiple methods to add text or image watermarks to PDF documents in a Spring Boot application, covering Java libraries such as Apache PDFBox, iText, Ghostscript command line, Free Spire.PDF, and Aspose.PDF, with code examples and usage instructions.
PDF (Portable Document Format) is widely used, and adding watermarks can improve document identification and protect copyright. This guide shows how to implement PDF watermarking in a Spring Boot environment using several Java libraries and tools.
Method 1: Apache PDFBox
PDFBox is a free, open‑source Java library for creating and manipulating PDFs. Add the dependency to pom.xml :
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.24</version>
</dependency>Load the original PDF, iterate over pages, and use PDPageContentStream to draw the watermark text:
PDDocument document = PDDocument.load(new File("original.pdf"));
for (int i = 0; i < document.getNumberOfPages(); i++) {
PDPage page = document.getPage(i);
PDPageContentStream cs = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true);
cs.setFont(PDType1Font.HELVETICA_BOLD, 36);
cs.setNonStrokingColor(200, 200, 200);
cs.beginText();
cs.newLineAtOffset(100, 100);
cs.showText("Watermark");
cs.endText();
cs.close();
}
document.save(new File("output.pdf"));
document.close();Method 2: iText
iText is another popular Java PDF library. Add the Maven dependency:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>Read the PDF and apply a watermark using PdfContentByte :
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 cb = stamper.getUnderContent(i);
cb.beginText();
cb.setFontAndSize(BaseFont.createFont(), 36f);
cb.setColorFill(BaseColor.LIGHT_GRAY);
cb.showTextAligned(Element.ALIGN_CENTER, "Watermark", 300, 400, 45);
cb.endText();
}
stamper.close();
reader.close();Method 3: Ghostscript (Command Line)
Ghostscript can add watermarks via a single command. After installing Ghostscript, run:
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.pdfThe command writes the watermark directly onto each page of original.pdf and produces output.pdf .
Method 4: Free Spire.PDF for Java
Free Spire.PDF is a free Java PDF library. Add its Maven dependency:
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>free-spire-pdf-for-java</artifactId>
<version>1.9.6</version>
</dependency>Load the PDF, create a PdfWatermark , and add it to each page:
PdfDocument pdf = new PdfDocument();
pdf.loadFromFile("original.pdf");
for (int i = 0; i < pdf.getPages().getCount(); i++) {
PdfPageBase page = pdf.getPages().get(i);
PdfWatermark wm = new PdfWatermark("Watermark");
wm.setFont(new PdfFont(PdfFontFamily.Helvetica, 36));
wm.setOpacity(0.5f);
page.getWatermarks().add(wm);
}
pdf.saveToFile("output.pdf");
pdf.close();Method 5: Aspose.PDF for Java (Spring Boot Integration)
Aspose.PDF provides powerful PDF manipulation. Add the dependency:
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-pdf</artifactId>
<version>21.4</version>
</dependency>Expose two REST endpoints to add text or image watermarks:
@PostMapping("/addTextWatermark")
public ResponseEntity
addTextWatermark(@RequestParam("file") MultipartFile file) throws IOException {
Document pdf = new Document(file.getInputStream());
TextStamp ts = new TextStamp("Watermark");
ts.setWordWrap(true);
ts.setVerticalAlignment(VerticalAlignment.Center);
ts.setHorizontalAlignment(HorizontalAlignment.Center);
pdf.getPages().get_Item(1).addStamp(ts);
ByteArrayOutputStream out = new ByteArrayOutputStream();
pdf.save(out);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"watermarked.pdf\"")
.contentType(MediaType.APPLICATION_PDF)
.body(out.toByteArray());
}
@PostMapping("/addImageWatermark")
public ResponseEntity
addImageWatermark(@RequestParam("file") MultipartFile file) throws IOException {
Document pdf = new Document(file.getInputStream());
ImageStamp is = new ImageStamp("watermark.png");
is.setWidth(100);
is.setHeight(100);
is.setVerticalAlignment(VerticalAlignment.Center);
is.setHorizontalAlignment(HorizontalAlignment.Center);
pdf.getPages().get_Item(1).addStamp(is);
ByteArrayOutputStream out = new ByteArrayOutputStream();
pdf.save(out);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"watermarked.pdf\"")
.contentType(MediaType.APPLICATION_PDF)
.body(out.toByteArray());
}These endpoints can be tested with tools like Postman by sending a multipart/form‑data request containing the PDF file.
Conclusion
The article presents five practical ways to add watermarks to PDFs in a Spring Boot project: using Apache PDFBox, iText, Ghostscript, Free Spire.PDF, and Aspose.PDF. Choose the approach that best fits your project requirements and be sure to back up original files before overwriting them.
Java Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.