給pdf文件添加水印
- 引入依賴
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.3</version>
</dependency>
- 添加水印
package com.it2.pdfdemo02.util;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import java.io.FileOutputStream;
/**
* @Description: PDF增加水印工具類
*/
public class PDFUtil {
/**
* 給PDF添加水印
* @param inputFilePath 源文件
* @param outputFilePath 生成的文件
* @param waterMarkContent 添加水印的內(nèi)容
*/
public static void pdfAddWaterMark(String inputFilePath, String outputFilePath, String waterMarkContent) {
try {
// 水印的高和寬
int waterMarkHeight = 30;
int watermarkWeight = 60;
// 水印間隔距離
int waterMarkInterval = 200;
// 讀取PDF文件流
PdfReader pdfReader = new PdfReader(inputFilePath);
// 創(chuàng)建PDF文件的模板,可以對(duì)模板的內(nèi)容修改,重新生成新PDF文件
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(outputFilePath));
// 設(shè)置水印字體
BaseFont baseFont = BaseFont.createFont("Font/SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); //幼圓常規(guī)
// 設(shè)置PDF內(nèi)容的Graphic State 圖形狀態(tài)
PdfGState pdfGraPhicState = new PdfGState();
// 填充透明度
pdfGraPhicState.setFillOpacity(0.2f);
// 輪廓不透明度
pdfGraPhicState.setStrokeOpacity(0.4f);
// PDF頁數(shù)
int pdfPageNum = pdfReader.getNumberOfPages() + 1;
// PDF文件內(nèi)容字節(jié)
PdfContentByte pdfContent;
// PDF頁面矩形區(qū)域
Rectangle pageRectangle;
for (int i = 1; i < pdfPageNum; i++) {
// 獲取當(dāng)前頁面矩形區(qū)域
pageRectangle = pdfReader.getPageSizeWithRotation(i);
// 獲取當(dāng)前頁內(nèi)容,getOverContent表示之后會(huì)在頁面內(nèi)容的上方加水印
pdfContent = pdfStamper.getOverContent(i);
// 獲取當(dāng)前頁內(nèi)容,getOverContent表示之后會(huì)在頁面內(nèi)容的下方加水印
// pdfContent = pdfStamper.getUnderContent(i);
pdfContent.saveState();
// 設(shè)置水印透明度
pdfContent.setGState(pdfGraPhicState);
// 開啟寫入文本
pdfContent.beginText();
// 設(shè)置字體
pdfContent.setFontAndSize(baseFont, 20);
// 在高度和寬度維度每隔waterMarkInterval距離添加一個(gè)水印
for (int height = waterMarkHeight; height < pageRectangle.getHeight(); height = height + waterMarkInterval) {
for (int width = watermarkWeight; width < pageRectangle.getWidth() + watermarkWeight;
width = width + waterMarkInterval) {
// 添加水印文字并旋轉(zhuǎn)30度角
pdfContent.showTextAligned(Element.ALIGN_LEFT, waterMarkContent, width - watermarkWeight,
height - waterMarkHeight, 30);
}
}
// 停止寫入文本
pdfContent.endText();
}
pdfStamper.close();
pdfReader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 添加字體文件到resoures\Font\simsun.ttc
用到的字體文件(幼圓常規(guī),C盤Windows/Fonts目錄下
文章來源:http://www.zghlxwxcb.cn/news/detail-733462.html
- 測(cè)試用例
@Test
void addWater() {
PDFUtil.pdfAddWaterMark("D:\\test3\\test1.pdf", "D:\\test3\\test1_watermark.pdf", "內(nèi)部資料,禁止外傳");
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-733462.html
到了這里,關(guān)于pdf添加水印的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!