業(yè)務(wù)背景:用戶在手機(jī)APP上進(jìn)行簽名,前端將簽完名字的圖片傳入后端,后端合成新的pdf.
廢話不多說,上代碼:
//控制層代碼
@PostMapping("/imageToPdf")
public Result imageToPdf(@RequestParam("linkName") String name, @RequestParam("file")
MultipartFile file) throws IOException {
try {
String format = LocalDateTimeUtil.format(LocalDateTime.now(),
DatePattern.PURE_DATETIME_MS_PATTERN);
File f = convertMultipartFileToFile(file);
//縮放圖片
ImgUtil.scale(FileUtil.file(f), FileUtil.file("/hetong/dev/image/" + format +
".png"), 0.06f);
// 旋轉(zhuǎn)270度
BufferedImage image = (BufferedImage)
//此處利用hutool工具類進(jìn)行縮放
ImgUtil.rotate(ImageIO.read(FileUtil.file("/hetong/dev/image/" + format +
".png")), 270);
ImgUtil.write(image, FileUtil.file("/hetong/dev/image/" + format + "_result" +
".png"));
String imagePath = "/hetong/dev/image/" + format + "_result" + ".png";
String fileUrl = name; // 要下載的文件的HTTPS鏈接
String localFilePath = "/hetong/dev/" + format + ".pdf"; // 下載文件保存到本地的路徑和名稱
//String localFilePath = "D:\\soft\\ceshi\\" + format + ".pdf"; // 下載文件保存到本地的路徑和名稱
downloadFile(fileUrl, localFilePath);
String pdfPath = localFilePath;
String url = imageToPdfUtil.addImageToPDF(imagePath, pdfPath, format);
return new Result(ResultCode.SUCCESS, url);
} catch (IOException e) {
e.printStackTrace();
}
return new Result(ResultCode.IMAGE_MERGE_FAILED, "");
}
//工具類
@Component
public class ImageToPdfUtil {
private static Logger logger = LoggerFactory.getLogger(WordUtil.class);
@Autowired
private UploadManager uploadManager;
@Autowired
private Auth auth;
@Value("${qiniu.bucketName}")
private String bucketName;
@Value("${qiniu.path}")
private String url;
/**
* 添加圖片至pdf指定位置
*
* @param imagePath
* @param pdfPath
* @throws IOException
*/
public String addImageToPDF(String imagePath, String pdfPath, String format) throws IOException {
// 加載圖片
PDDocument document = PDDocument.load(new File(pdfPath));
PDPage lastPage = document.getPage(document.getNumberOfPages() - 1);
PDImageXObject image = PDImageXObject.createFromFile(imagePath, document);
// 獲取圖片寬度和高度
float imageWidth = image.getWidth();
float imageHeight = image.getHeight();
try (PDPageContentStream contentStream = new PDPageContentStream(document, lastPage, PDPageContentStream.AppendMode.APPEND, true, true)) {
// 設(shè)置圖片位置
float x = (lastPage.getMediaBox().getWidth() / 2f - imageWidth / 2f) * 0.88f;
float y = (lastPage.getMediaBox().getHeight() / 2f - imageHeight / 2f) * 1.5f;
// 添加圖片到指定位置
contentStream.drawImage(image, x, y, imageWidth, imageHeight);
}
// 保存修改后的 PDF
document.save(pdfPath);
document.close();
return uploadQiniu(format);
}
/**
* 上傳到七牛云
*
* @param fileName
* @return
* @throws FileNotFoundException
* @throws QiniuException
*/
public String uploadQiniu(String fileName) throws FileNotFoundException, QiniuException {
//這里是上傳到服務(wù)器路徑下的,已經(jīng)填充完數(shù)據(jù)的word
File file = ResourceUtils.getFile("/hetong/dev/" + fileName + ".pdf");
//File file = ResourceUtils.getFile("D:\\soft\\ceshi\\" + fileName + ".pdf");
//FileInputStream uploadFile = (FileInputStream) file.getInputStream();
// 獲取文件輸入流
FileInputStream inputStream = new FileInputStream(file);
//這個是已經(jīng)填充完整的數(shù)據(jù)后上傳至七牛云鏈接
String path = "http://" + upload(inputStream, fileName);
logger.info("上傳至七牛云的合同路徑==path==" + path);
return path;
}
public String upload(FileInputStream file, String fileName) throws QiniuException {
String token = auth.uploadToken(bucketName);
Response res = uploadManager.put(file, fileName, token, null, null);
if (!res.isOK()) {
throw new RuntimeException("上傳七牛云出錯:" + res);
}
return url + "/" + fileName;
}
public static void main(String[] args) {
try {
// 指定原始圖片路徑
File originalImage = new File("D:\\soft\\ceshi\\20230901204201606.png");
// 指定壓縮后保存的目標(biāo)路徑
File compressedImage = new File("D:\\soft\\ceshi\\20230901204201606_result.png");
// 壓縮和縮放圖片
Thumbnails.of(originalImage)
.scale(0.1) // 縮放比例為50%
.outputQuality(0.9) // 圖片質(zhì)量為80%
.toFile(compressedImage);
System.out.println("圖片壓縮和縮放完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* MultipartFile 轉(zhuǎn)file
*
* @param multipartFile
* @return
* @throws IOException
*/
public static File convertMultipartFileToFile(MultipartFile multipartFile) throws IOException {
byte[] fileBytes = multipartFile.getBytes();
File tempFile = File.createTempFile("temp", null);
try (OutputStream outputStream = new FileOutputStream(tempFile)) {
outputStream.write(fileBytes);
}
return tempFile;
}
/**
* 根號https鏈接下載文檔
*
* @param fileUrl
* @param localFilePath
* @throws IOException
*/
public static void downloadFile(String fileUrl, String localFilePath) throws IOException {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream());
FileOutputStream outputStream = new FileOutputStream(localFilePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
connection.disconnect();
}
}
注意:前端傳過來的圖片必須是透明的,否則合成的時候簽名處會有邊框
? ? ?文章來源:http://www.zghlxwxcb.cn/news/detail-703502.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-703502.html
到了這里,關(guān)于Java 利用pdfbox將圖片和成到pdf指定位置的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!