feat: 加水印改为动态字号

This commit is contained in:
2024-01-02 17:25:22 +08:00
parent 9e0570b777
commit fe4d15a894
4 changed files with 33 additions and 24 deletions
@@ -51,10 +51,11 @@ public class WaterMarkUtil {
String watermarkText = getWaterMarkConfig();
PDDocument document = PDDocument.load(inputStream);
// 设置水印字体、字体大小、颜色和透明度
// 加载水印字体
ClassPathResource fontResource = new ClassPathResource("fonts/SourceHanSerif-VF.ttf");
PDType0Font font = PDType0Font.load(document, fontResource.getInputStream());
float fontSize = this.fontSize;
// 设置水印颜色和透明度
Color color = new Color(r, g, b, a);
PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState();
graphicsState.setNonStrokingAlphaConstant(0.4f);
@@ -62,18 +63,24 @@ public class WaterMarkUtil {
// 遍历每一页并添加水印
for (PDPage page : document.getPages()) {
// 获取页面尺寸以计算水印位置
// 获取页面尺寸以计算水印位置和大小
PDRectangle pageSize = page.getMediaBox();
float xStep = pageSize.getWidth() / 4;
float yStep = pageSize.getHeight() / 4;
float pageWidth = pageSize.getWidth();
float pageHeight = pageSize.getHeight();
// 根据页面宽度动态调整字体大小
float dynamicFontSize = pageWidth * (this.fontSize / 595); // 假设基准页面宽度为595单位
float xStep = pageWidth / 4;
float yStep = pageHeight / 4;
float rotationInRadians = (float) Math.toRadians(20);
for (float xPosition = pageSize.getLowerLeftX(); xPosition <= pageSize.getWidth(); xPosition += xStep) {
for (float yPosition = pageSize.getLowerLeftY(); yPosition <= pageSize.getHeight(); yPosition += yStep) {
for (float xPosition = pageSize.getLowerLeftX(); xPosition <= pageWidth; xPosition += xStep) {
for (float yPosition = pageSize.getLowerLeftY(); yPosition <= pageHeight; yPosition += yStep) {
// 创建内容流并设置图形状态参数
try (PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true)) {
contentStream.setGraphicsStateParameters(graphicsState);
contentStream.setFont(font, fontSize);
contentStream.setFont(font, dynamicFontSize);
contentStream.setNonStrokingColor(color);
contentStream.beginText();
contentStream.setRenderingMode(RenderingMode.FILL);
@@ -94,4 +101,5 @@ public class WaterMarkUtil {
// 将ByteArrayOutputStream转换为ByteArrayInputStream以供返回
return new ByteArrayInputStream(baos.toByteArray());
}
}