SpringBoot 實現 PDF 新增水印

KLAPT發表於2024-10-24

方式一:使用 Apache PDFBox 庫

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 新增水印:
// 遍歷 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();
}

最後,需要儲存修改後的 PDF 檔案:

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

方式二:使用 iText 庫

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 新增水印:

// 獲取 PDF 中的頁數
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 檔案並關閉檔案流:

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





方式三:用 Ghostscript 命令列

1. Ghostscript

首先需要在本地安裝 Ghostscript 程式。

Windows: https://www.ghostscript.com/download/gsdnld.html

macOS: https://www.ghostscript.com/download/gsdnld.html

Linux: https://www.ghostscript.com/download/gsdnld.html

2. 新增水印


可以在終端中使用 Ghostscript 的命令列工具執行以下命令來實現:


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;最後一個引數 original.pdf 則表示原始 PDF 檔案的路徑;中間的字串則表示新增的水印內容。


3. 注意事項


使用 Ghostscript 命令列新增水印時,會直接修改原始 PDF 檔案,因此建議先備份原始檔案。


方式四:Free Spire.PDF for Java


下面介紹一下使用 Free Spire.PDF for Java 實現 PDF 新增水印的方式。


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 新增水印:


// 遍歷 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 的引數修改為圖片路徑即可。


// 新增圖片水印
PdfWatermark watermark = new PdfWatermark("watermark.png");
watermark.setOpacity(0.5f);
page.getWatermarks().add(watermark);
方式五:Aspose.PDF for Java

在 pom.xml 檔案中新增 Aspose.PDF for Java 的依賴:

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

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

相關文章