Commit ba07061c authored by suhuiguang's avatar suhuiguang

1,增加生成pdf的水印方法

parent 1bcb366d
......@@ -5,6 +5,7 @@ import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.module.jg.api.service.IJgInstallationNoticeService;
import com.yeejoin.amos.boot.module.jg.biz.service.ICommonService;
import com.yeejoin.amos.boot.module.jg.biz.service.IPdfService;
import com.yeejoin.amos.boot.module.ymt.api.entity.EquipmentCategory;
import com.yeejoin.amos.boot.module.ymt.api.enums.FlowStatusEnum;
import io.swagger.annotations.Api;
......@@ -33,6 +34,9 @@ public class CommonController extends BaseController {
@Autowired
ICommonService commonService;
@Autowired
IPdfService pdfService;
@TycloudOperation(ApiLevel = UserType.AGENCY)
@GetMapping(value = "/getChildren")
@ApiOperation(httpMethod = "GET", value = "通过设备种类code获取设备类别", notes = "通过设备种类code获取设备类别")
......@@ -305,4 +309,19 @@ public class CommonController extends BaseController {
}
@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
@GetMapping(value = "/test-file")
@ApiOperation(httpMethod = "GET", value = "文件测试", notes = "文件测试")
public ResponseModel<String> testFile() {
return ResponseHelper.buildResponse(pdfService.signToPdf("upload/tzs/pdf/1708911268708_temp.pdf", "已作废"));
}
@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
@GetMapping(value = "/water-print")
@ApiOperation(httpMethod = "GET", value = "文件测试", notes = "文件测试")
public ResponseModel<String> signToPdfWaterPrint() {
return ResponseHelper.buildResponse(pdfService.signToPdfWaterPrint("upload/tzs/pdf/1708911268708_temp.pdf", "已作废"));
}
}
package com.yeejoin.amos.boot.module.jg.biz.service;
/**
* @author Administrator
*/
public interface IPdfService {
/**
* pdf 增加图片
* @param inputPdfPath 输入pdf 文件路径
* @param text 图片路径
* @return pdf文件 路径
*/
String signToPdf(String inputPdfPath, String text);
/**
* pdf 增加图片水印
* @param inputPdfPath 输入pdf 文件路径
* @param text 图片路径
* @return pdf文件 路径
*/
String signToPdfWaterPrint(String inputPdfPath, String text);
}
package com.yeejoin.amos.boot.module.jg.biz.service.impl;
import com.yeejoin.amos.boot.module.jg.biz.service.IPdfService;
import com.yeejoin.amos.boot.module.jg.biz.utils.PdfUtils;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
/**
* @author Administrator
*/
@Component
public class PdfServiceImpl implements IPdfService {
@Value("${fileserver.domain}")
private String fileServerUrl;
@Override
public String signToPdf(String inputPdfPath, String text) {
String newFilePath = "";
String filePath = fileServerUrl + inputPdfPath;
File imageFile = null, file = null;
try {
imageFile = File.createTempFile("temp", ".png");
PdfUtils.generatorImageWithText(imageFile, 100, 50, text , Color.RED);
file = PdfUtils.addImageToPdf(filePath, 100, 50, imageFile.getAbsolutePath());
String fileName = extractFileNameFromPath(inputPdfPath);
MultipartFile mockMultipartFile = new MockMultipartFile(fileName, fileName, ContentType.APPLICATION_OCTET_STREAM.toString(), new FileInputStream(file));
FeignClientResult<Map<String, String>> result = Systemctl.fileStorageClient.updateCommonFileFree(mockMultipartFile, "upload/tzs/pdf");
Map<String, String> map = result.getResult();
for (Map.Entry<String, String> fileResult : map.entrySet()) {
newFilePath = fileResult.getKey();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(imageFile != null){
imageFile.deleteOnExit();
}
if(file != null){
file.deleteOnExit();
}
}
return newFilePath;
}
@Override
public String signToPdfWaterPrint(String inputPdfPath, String text) {
String newFilePath = "";
String filePath = fileServerUrl + inputPdfPath;
File imageFile = null, file = null;
try {
imageFile = File.createTempFile("temp", ".png");
PdfUtils.generatorImageWithText(imageFile, 200, 100, text , Color.RED);
file = PdfUtils.addFullPageWatermark(filePath, "已作废");
String fileName = extractFileNameFromPath(inputPdfPath);
MultipartFile mockMultipartFile = new MockMultipartFile(fileName, fileName, ContentType.APPLICATION_OCTET_STREAM.toString(), new FileInputStream(file));
FeignClientResult<Map<String, String>> result = Systemctl.fileStorageClient.updateCommonFileFree(mockMultipartFile, "upload/tzs/pdf");
Map<String, String> map = result.getResult();
for (Map.Entry<String, String> fileResult : map.entrySet()) {
newFilePath = fileResult.getKey();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(imageFile != null){
imageFile.deleteOnExit();
}
if(file != null){
file.deleteOnExit();
}
}
return newFilePath;
}
private static String extractFileNameFromPath(String path) {
// 查找最后一个斜杠的位置
int lastIndex = path.lastIndexOf('/');
// 如果找不到斜杠,说明没有目录,整个字符串就是文件名
if (lastIndex == -1) {
return path;
}
// 否则,从最后一个斜杠之后开始提取文件名
return path.substring(lastIndex + 1);
}
}
package com.yeejoin.amos.boot.module.jg.biz.utils;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.SneakyThrows;
import javax.imageio.ImageIO;
import java.awt.Font;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author Administrator
*/
public class PdfUtils {
@SneakyThrows
public static File addImageToPdf(String inputPdfPath, int width, int height, String imagePath) {
PdfReader reader = null;
PdfStamper stamper = null;
File outputPdfFile = null;
try {
reader = new PdfReader(inputPdfPath);
outputPdfFile = File.createTempFile("output", ".pdf");
stamper = new PdfStamper(reader, new FileOutputStream(outputPdfFile));
Image img = Image.getInstance(imagePath);
img.scaleToFit(width, height);
PdfContentByte content = stamper.getOverContent(1);
img.setAbsolutePosition(reader.getPageSize(1).getWidth() - width, reader.getPageSize(1).getHeight() - height);
content.addImage(img);
} catch (IOException | DocumentException e) {
e.printStackTrace();
} finally {
if (stamper != null) {
try {
stamper.close();
} catch (DocumentException | IOException e) {
e.printStackTrace();
}
}
if (reader != null) {
reader.close();
}
}
return outputPdfFile;
}
public static void generatorImageWithText(File imageFile, int width, int height, String text, Color color) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
// 设置背景为透明
image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
g2d.dispose();
g2d = image.createGraphics();
// 设置抗锯齿
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 写入字符串
Font font = new Font("Microsoft YaHei", Font.BOLD, 20);
g2d.setFont(font);
FontMetrics fm = g2d.getFontMetrics();
int textWidth = fm.stringWidth(text);
int textHeight = fm.getHeight();
int x = (width - textWidth) / 2;
int y = (height - textHeight) / 2 + fm.getAscent();
g2d.setColor(color);
g2d.drawString(text, x, y);
g2d.dispose();
try {
ImageIO.write(image, "PNG", imageFile);
} catch (IOException e) {
e.printStackTrace();
}
}
@SneakyThrows
public static File addFullPageWatermark(String src, String watermarkText) {
PdfReader reader = null;
PdfStamper stamper = null;
File outputPdfFile = null;
try {
outputPdfFile = File.createTempFile("output", ".pdf");
reader = new PdfReader(src);
stamper = new PdfStamper(reader, new FileOutputStream(outputPdfFile));
stamper.setFormFlattening(true);
PdfGState gs = new PdfGState();
// 设置透明度为0.1
gs.setFillOpacity(0.2f);
int n = reader.getNumberOfPages();
// 创建一个BaseFont实例,用于水印文本
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
// 设置水印文本大小
float fontSize = 40;
// 设置水印文本的间距、根据字体大小调整行间距
float lineSpacing = fontSize + 2;
// 设置水印文本的起始位置
float x = 0;
// 遍历PDF的每一页
for (int i = 1; i <= n; i++) {
PdfContentByte over = stamper.getUnderContent(i);
// 获取页面尺寸
Rectangle pageSize = reader.getPageSizeWithRotation(i);
float pageWidth = pageSize.getWidth();
float pageHeight = pageSize.getHeight();
// 从页面底部开始
float y = pageHeight;
// 计算文本宽度
float textWidth = bf.getWidthPoint(watermarkText, fontSize);
// 添加水印文本到页面
while (y > 0) {
// 文本从页面左侧开始
x = 60;
while (x < pageWidth) {
over.beginText();
over.setFontAndSize(bf, fontSize);
//水印颜色
over.setColorFill(BaseColor.BLACK);
over.setGState(gs);
over.setTextMatrix(x, y);
over.showTextAligned(Element.ALIGN_CENTER, watermarkText, x, y, 45);
over.endText();
// 更新x坐标以跳过当前行的文本宽度
x += textWidth + lineSpacing;
}
// 当一行文本添加完毕后,减少y坐标以开始新的一行
y -= (lineSpacing + 50);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stamper != null) {
stamper.close();
}
if (reader != null) {
reader.close();
}
}
return outputPdfFile;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment