Source: cnblogs.com/hushaojun/p/16285486.html
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 watermarks to PDF files to make them more recognizable or to protect their copyright. This article will introduce how to use Spring Boot to add watermarks to PDFs.
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.
Recommend an open source and free Spring Boot practical project:
https://github.com/javastacks/spring-boot-best-practice
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 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();
Full 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 dependencies 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();
Full code
The following is the complete code for 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: Use Ghostscript command line
Ghostscript is a popular, free, open source PDF processing program that can be used to create, read, modify, and extract PDF content. Command line parameters are provided in Ghostscript to add watermarks.
Ghostscript
First you need to install the Ghostscript program locally. The installation package can be downloaded through the following link:
- Windows[1]
- macOS[2]
- Linux[3]
Add watermark
This can be achieved by executing the following command in the terminal using Ghostscript’s command line tool:
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
In the above command, -sDEVICE=pdfwrite
means the output is a PDF file; -sOutputFile=output.pdf
means the output file name is output.pdf
; The last parameter original.pdf
represents the path of the original PDF file; the middle string represents the added watermark content.
Notes
When adding a watermark using the Ghostscript command line, the original PDF file will be directly modified, so it is recommended to back up the original file first.
Method 4: 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 change 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);
Full 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 5: 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.
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 { //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 from 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.
Conclusion
This article introduces several ways to use Spring Boot to add watermarks to PDFs, including using the Apache PDFBox library, iText library, and Ghostscript command line. Which method to choose can be decided based on project needs and personal preference. No matter which method you use, you need to pay attention to protecting the original PDF file and not modifying the original file directly unnecessarily. Welcome to like and collect it. When your boss arranges for you to do this, I hope you can find the relevant Java tool library in time to realize this function.
Recommended recent hot articles:
1.1,000+ Java interview questions and answers compiled (2022 latest version)
2. Explosive! Java coroutines are coming. . .
3. Spring Boot 2.x tutorial, so complete!
4. Stop filling the screen with explosive categories and try the decorator mode. This is the elegant way! !
5. “Java Development Manual (Songshan Edition)” is newly released, download it quickly!
If you think it’s good, don’t forget to like + retweet!