SpringBoot實現(xiàn)PDF添加水印的示例
簡介
PDF(Portable Document Format,便攜式文檔格式)是一種流行的文件格式,它可以在多個操作系統(tǒng)和應(yīng)用程序中進行查看和打印。在某些情況下,我們需要對 PDF 文件添加水印,以使其更具有辨識度或者保護其版權(quán)。本文將介紹如何使用 Spring Boot 來實現(xiàn) PDF 添加水印的方式。
方式1:使用 Apache PDFBox 庫
PDFBox 是一個流行的、免費的、用 Java 編寫的庫,它可以用來創(chuàng)建、修改和提取 PDF 內(nèi)容。PDFBox 提供了許多 API,包括添加文本水印的功能。
(1)添加 PDFBox 依賴
首先,在 pom.xml
文件中添加 PDFBox 的依賴:
<dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.24</version> </dependency>
(2)添加水印
在添加水印之前,需要讀取原始 PDF 文件:
PDDocument document = PDDocument.load(new File("original.pdf"));
然后,遍歷 PDF 中的所有頁面,并使用 PDPageContentStream
添加水?。?/p>
// 遍歷 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); // 設(shè)置字體和字號 contentStream.setFont(PDType1Font.HELVETICA_BOLD, 36); // 設(shè)置透明度 contentStream.setNonStrokingColor(200, 200, 200); // 添加文本水印 contentStream.beginText(); contentStream.newLineAtOffset(100, 100); // 設(shè)置水印位置 contentStream.showText("Watermark"); // 設(shè)置水印內(nèi)容 contentStream.endText(); contentStream.close(); }
最后,需要保存修改后的 PDF 文件:
document.save(new File("output.pdf")); document.close();
(3)完整代碼
下面是使用 PDFBox 來實現(xiàn) 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 { // 讀取原始 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); // 設(shè)置字體和字號 contentStream.setFont(PDType1Font.HELVETICA_BOLD, 36); // 設(shè)置透明度 contentStream.setNonStrokingColor(200, 200, 200); // 添加文本水印 contentStream.beginText(); contentStream.newLineAtOffset(100, 100); // 設(shè)置水印位置 contentStream.showText("Watermark"); // 設(shè)置水印內(nèi)容 contentStream.endText(); contentStream.close(); } // 保存修改后的 PDF 文件 document.save(new File("output.pdf")); document.close(); } }
方式2:使用 iText 庫
iText 是一款流行的 Java PDF 庫,它可以用來創(chuàng)建、讀取、修改和提取 PDF 內(nèi)容。iText 提供了許多 API,包括添加文本水印的功能。
(1)添加 iText 依賴
在 pom.xml
文件中添加 iText 的依賴:
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13</version> </dependency>
(2)添加水印
在添加水印之前,需要讀取原始 PDF 文件:
PdfReader reader = new PdfReader("original.pdf"); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("output.pdf"));
然后,遍歷 PDF 中的所有頁面,并使用 PdfContentByte
添加水?。?/p>
// 獲取 PDF 中的頁數(shù) 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 文件并關(guān)閉文件流:
stamper.close(); reader.close();
(3)完整代碼
下面是使用 iText 來實現(xiàn) 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 { // 讀取原始 PDF 文件 PdfReader reader = new PdfReader("original.pdf"); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("output.pdf")); // 獲取 PDF 中的頁數(shù) 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 文件并關(guān)閉文件流 stamper.close(); reader.close(); } }
方式3:使用 Ghostscript 命令行
Ghostscript 是一款流行的、免費的、開源的 PDF 處理程序,它可以用來創(chuàng)建、讀取、修改和提取 PDF 內(nèi)容。Ghostscript 中提供了命令行參數(shù)來添加水印。
(1)安裝 Ghostscript
首先需要在本地安裝 Ghostscript 程序。可通過以下鏈接下載安裝包:
(2)添加水印
可以在終端中使用 Ghostscript 的命令行工具執(zhí)行以下命令來實現(xiàn):
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
上述命令中,-sDEVICE=pdfwrite
表示輸出為 PDF 文件;-sOutputFile=output.pdf
表示輸出文件名為 output.pdf
;最后一個參數(shù) original.pdf
則表示原始 PDF 文件的路徑;中間的字符串則表示添加的水印內(nèi)容。
(3)注意事項
使用 Ghostscript 命令行添加水印時,會直接修改原始 PDF 文件,因此建議先備份原始文件。
方式4:Free Spire.PDF for Java
下面介紹一下使用 Free Spire.PDF for Java 實現(xiàn) PDF 添加水印的方式。
Free Spire.PDF for Java 是一款免費的 Java PDF 庫,它提供了一個簡單易用的 API,用于創(chuàng)建、讀取、修改和提取 PDF 內(nèi)容。Free Spire.PDF for Java 也支持添加文本水印以及圖片水印。
(1)添加 Free Spire.PDF for Java 依賴
首先,在 pom.xml
文件中添加 Free Spire.PDF for Java 的依賴:
<dependency> <groupId>e-iceblue</groupId> <artifactId>free-spire-pdf-for-java</artifactId> <version>1.9.6</version> </dependency>
(2)添加水印
(2.1)添加文本水印
在添加水印之前,需要讀取原始 PDF 文件:
PdfDocument pdf = new PdfDocument(); pdf.loadFromFile("original.pdf");
然后,遍歷 PDF 中的所有頁面,并使用 PdfPageBase
添加水?。?/p>
// 遍歷 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); }
最后,需要保存修改后的 PDF 文件
pdf.saveToFile("output.pdf"); pdf.close();
(2.2)添加圖片水印
添加圖片水印與添加文本水印類似,只需要將 PdfWatermark
的參數(shù)修改為圖片路徑即可。
// 添加圖片水印 PdfWatermark watermark = new PdfWatermark("watermark.png"); watermark.setOpacity(0.5f); page.getWatermarks().add(watermark);
(3)完整代碼
下面是使用 Free Spire.PDF for Java 來實現(xiàn) PDF 添加水印的完整代碼:
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(); } }
方式5:Aspose.PDF for Java
Aspose.PDF for Java 是一個強大的 PDF 處理庫,提供了添加水印的功能。結(jié)合 Spring Boot 使用 Aspose.PDF for Java 庫添加 PDF 水印的方式如下:
首先,在 pom.xml
文件中添加 Aspose.PDF for Java 的依賴:
<dependency> <groupId>com.aspose</groupId> <artifactId>aspose-pdf</artifactId> <version>21.4</version> </dependency>
在 Spring Boot 應(yīng)用程序中調(diào)用 Aspose.PDF for Java 的 API 設(shè)置 PDF 水印。
(1) 添加文本水印
@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()); }
(2) 添加圖片水印
@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()); }
注意,以上代碼中的文件名、寬度、高度等參數(shù)需要根據(jù)實際情況進行調(diào)整。
完整的 Spring Boot 控制器類代碼如下:
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()); } }
這里使用了兩個 RESTful API:/addTextWatermark
和 /addImageWatermark
,分別用于添加文本水印和圖片水印。在請求中通過 file
參數(shù)傳遞 PDF 文件。
下面介紹如何使用 Postman 來測試 Spring Boot 應(yīng)用程序的 API。
- 下載并安裝 Postman。
- 打開 Postman,選擇 POST 請求方法。
- 在 URL 地址欄中輸入
http://localhost:8080/api/pdf/addTextWatermark
。 - 在 Headers 標(biāo)簽頁中設(shè)置 Content-Type 為 multipart/form-data。
- 在 Body 標(biāo)簽頁中選擇 form-data 類型,然后設(shè)置 key 為
file
,value 選擇本地的 PDF 文件。 - 點擊 Send 按鈕發(fā)送請求,等待應(yīng)答結(jié)果。
處理結(jié)果將會在響應(yīng)的 Body 中返回,也可以選擇瀏覽器下載或保存到本地磁盤。
以上就是使用 Aspose.PDF for Java 庫結(jié)合 Spring Boot 添加 PDF 水印的方式。
結(jié)論
本文介紹了幾種使用 Spring Boot 實現(xiàn) PDF 添加水印的方式,分別是使用 Apache PDFBox 庫、iText 庫以及 Ghostscript 命令行等。選擇哪種方式,可以根據(jù)項目需求和個人偏好來決定。無論采用哪種方式,都需要注意保護原始 PDF 文件,不要在不必要的情況下直接修改原始文件。歡迎點贊收藏,在你老板安排你干這時,希望你能夠及時找到相關(guān)的Java工具庫,實現(xiàn)這項功能。
到此這篇關(guān)于SpringBoot實現(xiàn)PDF添加水印的示例的文章就介紹到這了,更多相關(guān)SpringBoot PDF添加水印內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于Spring + Spring MVC + Mybatis 高性能web構(gòu)建實例詳解
這篇文章主要介紹了基于Spring + Spring MVC + Mybatis 高性能web構(gòu)建實例詳解,需要的朋友可以參考下2017-04-04Java語言----三種循環(huán)語句的區(qū)別介紹
下面小編就為大家?guī)硪黄狫ava語言----三種循環(huán)語句的區(qū)別介紹。小編舉得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-07-07Java如何使用ReentrantLock實現(xiàn)長輪詢
這篇文章主要介紹了如何使用ReentrantLock實現(xiàn)長輪詢,對ReentrantLock感興趣的同學(xué),可以參考下2021-04-04SpringMVC的組件之HandlerExceptionResolver詳解
這篇文章主要介紹了SpringMVC的組件之HandlerExceptionResolver詳解,不管是在處理請求映射(HandlerMapping),還是在請求被處理(Handler)時拋出的異常,DispatcherServlet都會委托給HandlerExceptionResolver進行異常處理,該接口只有一個方法,需要的朋友可以參考下2023-10-10淺談java Iterator.remove()方法的用法(詳解)
下面小編就為大家?guī)硪黄獪\談java Iterator.remove()方法的用法(詳解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01