1. 添加pom依賴pom.xml
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
itextpdf
可以兼容中文
2. 創(chuàng)建工具類WatermarkUtils.java
public class WaterMarkUtils {
public static OutputStream addWaterMark(byte[] bytes, OutputStream outputStream, String text, int textWidth, int textHeight,
String imgFile, int imgWidth, int imgHeight) throws IOException, DocumentException {
// 待加水印的文件
PdfReader reader = new PdfReader(bytes);
// 加完水印的文件
PdfStamper stamper = new PdfStamper(reader, outputStream);
// 設(shè)置字體
BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED); // 華文宋體
//BaseFont font = BaseFont.createFont("C:\\Windows\\Fonts\\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); // 標(biāo)準(zhǔn)黑體
// 水印透明度
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.5f);
gs.setStrokeOpacity(0.5f);
// PDF總頁數(shù)
int total = reader.getNumberOfPages() + 1;
// 循環(huán)對每頁插入水印
PdfContentByte content;
for (int i = 1; i < total; i++) {
// 水印在之前文本之上
content = stamper.getOverContent(i);
// 透明度
content.setGState(gs);
// 圖片水印
if (imgFile != null) {
Image image = null;
if (imgFile != null) {
image = Image.getInstance(imgFile);
image.setAbsolutePosition(imgWidth, imgHeight);
// 設(shè)置圖片的顯示大小
image.scaleToFit(100, 125);
}
content.addImage(image);
}
// 文字水印
if (text != null) {
content.beginText();
// 設(shè)置顏色 默認(rèn)為藍(lán)色
content.setColorFill(new BaseColor(204, 204, 204));
//content.setColorFill(Color.BLUE);
// 設(shè)置字體及字號
content.setFontAndSize(font, 25);
// 設(shè)置起始位置
content.setTextMatrix(textWidth, textHeight);
// 字符間距
content.setCharacterSpacing(2);
// 中間水印
content.showTextAligned(Element.ALIGN_LEFT, text, textWidth, textHeight, 45);
// 底部水印
// for (int k = 0; k < text.length(); k++) {
// // 距離底邊的距離
// content.setTextRise(10);
//
// // 將char轉(zhuǎn)成字符串
// content.showText(String.valueOf(text.charAt(k)));
// }
content.endText();
}
}
stamper.close();
reader.close();
return outputStream;
}
}
3. 從URL獲取文件二進(jìn)制數(shù)據(jù)HttpRequestUtils.java
public class HttpRequestUtils {
/**
* 發(fā)送get請求 返回byte
* @param url 路徑
* @return
*/
public static byte[] httpGetFile(String url){
//get請求返回結(jié)果
byte[] byteResult = null;
try {
CloseableHttpClient client = HttpClients.createDefault();
//發(fā)送get請求
HttpGet request = new HttpGet(url);
CloseableHttpResponse response = client.execute(request);
try {
/**請求發(fā)送成功,并得到響應(yīng)**/
if (response.getStatusLine().getStatusCode() == 200) {
byteResult = EntityUtils.toByteArray(response.getEntity());
} else {
logger.error("get請求提交失敗:" + url);
}
} finally {
response.close();
}
} catch (IOException e) {
logger.error("get請求提交失敗:" + url, e);
}
return byteResult;
}
}
4. 給文件加水印實例
@RestController
@ResponseBody
@RequestMapping(value = "/api/demo")
public class DemoController {
@GetMapping("/addWaterPdf")
public ResponseEntity<byte[]> addWaterPdf(String url) throws Exception{
// url中獲取文件流
byte[] buffer = HttpRequestUtils.httpGetFile(url);
if (Objects.isNull(buffer) || buffer.length == 0) {
throw new RuntimeException("文件不存在");
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();// 輸出流實例
String waterText = "這是一個水印";
WatermarkUtils.addWaterMark(buffer, baos, waterText,20, 30, null, 400, 500);
HttpHeaders headers = new HttpHeaders();
// header只支持ASCII鸽凶,需要把中文通過ISO-8859-1重新編碼
String fileName = new String("水印文件.pdf".getBytes("utf-8"), "iso-8859-1");
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(baos.toByteArray(), headers, HttpStatus.OK);
}
}