当前位置: 首页 > news >正文

Java 利用pdfbox将图片和成到pdf指定位置

业务背景:用户在手机APP上进行签名,前端将签完名字的图片传入后端,后端合成新的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);// 旋转270度BufferedImage image = (BufferedImage) 
//此处利用hutool工具类进行缩放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);@Autowiredprivate UploadManager uploadManager;@Autowiredprivate 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)) {// 设置图片位置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);}// 保存修改后的 PDFdocument.save(pdfPath);document.close();return uploadQiniu(format);}/*** 上传到七牛云** @param fileName* @return* @throws FileNotFoundException* @throws QiniuException*/public String uploadQiniu(String fileName) throws FileNotFoundException, QiniuException {//这里是上传到服务器路径下的,已经填充完数据的wordFile 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);//这个是已经填充完整的数据后上传至七牛云链接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");// 指定压缩后保存的目标路径File compressedImage = new File("D:\\soft\\ceshi\\20230901204201606_result.png");// 压缩和缩放图片Thumbnails.of(originalImage).scale(0.1) // 缩放比例为50%.outputQuality(0.9) // 图片质量为80%.toFile(compressedImage);System.out.println("图片压缩和缩放完成!");} catch (IOException e) {e.printStackTrace();}}/*** MultipartFile 转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.lryc.cn/news/155533.html

相关文章:

  • 大数据课程K19——Spark的电影推荐案例推荐系统的冷启动问题
  • Docker-安装(Linux,Windows)
  • 若依富文本 html样式 被过滤问题
  • VS Code 快速消除前置空格和常用快捷键
  • 【跟小嘉学 Rust 编程】二十五、Rust命令行参数解析库(clap)
  • gRPC远程进程调用
  • 什么是继承
  • QT连接数据库
  • navicat访问orcal数据库
  • Linux中查找某路径下,包含某个字符串的所有文件
  • 常见信号滤波方法(卡尔曼滤波、滑动平均、异常值剔除)的原理解析与C语言实现
  • WebGL模型矩阵
  • Flutter:WebSocket封装-实现心跳、重连机制
  • c语言中:struct timespec
  • Mendix如何实现导出文件
  • 在IIS服务器上安装SSL证书(2023配置启用HTTPS部署教程)内容来源SSL市场网
  • 如何处理ChatGPT与用户之间的互动和反馈?
  • 微服务-gateway鉴权
  • NET7快速开发一个商品管理模块-商品列表开发(一)
  • 0829|C++day7 auto、lambda、C++数据类型转换、C++标准模板库(STL)、list、文件操作
  • SpringBoot连接MySQL数据库实例【tk.mybatis连接mysql数据库】
  • node基础之三:http 模块
  • 【高阶数据结构】AVL树 {概念及实现;节点的定义;插入并调整平衡因子;旋转操作:左单旋,右单旋,左右双旋,右左双旋;AVL树的验证及性能分析}
  • Netty—FuturePromise
  • 固定资产卡片乱怎么管理
  • AutoHotkey(AHK)脚本,自动截图当前屏幕并发送给微信窗口
  • Golang - go build打包文件
  • Java的归并排序
  • B. The Walkway Codeforces Round 893 (Div. 2)
  • 第四篇 DirectShow 采集调用结构关系