在springboot项目中实现将上传的jpg图片类型转为pdf并保存到本地

前言:前端使用uniapp中的uni.canvasToTempFilePath方法将画板中的内容保存为jpg上传至后端处理

uni.canvasToTempFilePath({canvasId: 'firstCanvas',sourceType: ['album'],fileType: "jpg",success: function (res1) {let signature_base64 = res1.tempFilePath;let signature_file = that.base64toFile(signature_base64);// 将签名存储到服务器uni.uploadFile({url: "convertJpgToPdf",name: "file",file: signature_file,formData: {busiId: 'ceshi12',token: token},success: function (res1) {console.log(res1);}})}});// 将base64转为filebase64toFile: function(base64String) {// 从base64字符串中解析文件类型var mimeType = base64String.match(/^data:(.*);base64,/)[1];// 生成随机文件名var randomName = Math.random().toString(36).substring(7);var filename = randomName + '.' + mimeType.split('/')[1];let arr = base64String.split(",");let bstr = atob(arr[1]);let n = bstr.length;let u8arr = new Uint8Array(n);while (n--) {u8arr[n] = bstr.charCodeAt(n);}return new File([u8arr], filename, { type: mimeType });},

java代码:
首先在pom.xml中安装依赖

<dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.8</version>
</dependency>

使用方法:

/*** 将jpg转为pdf文件* @param jpgFile* @return* @throws IOException*/public MultipartFile convertJpgToPdf(MultipartFile jpgFile) throws IOException {// 保存MultipartFile到临时文件File tempFile = new File(System.getProperty("java.io.tmpdir"), "temp.jpg");jpgFile.transferTo(tempFile);// 创建PDF文档PDDocument pdfDoc = new PDDocument();PDPage pdfPage = new PDPage();pdfDoc.addPage(pdfPage);// 从临时文件创建PDImageXObjectPDImageXObject pdImage = PDImageXObject.createFromFile(tempFile.getAbsolutePath(), pdfDoc);// 获取PDF页面的内容流以添加图像PDPageContentStream contentStream = new PDPageContentStream(pdfDoc, pdfPage);// 获取PDF页面的大小PDRectangle pageSize = pdfPage.getMediaBox();float pageWidth = pageSize.getWidth();float pageHeight = pageSize.getHeight();// 在PDF页面上绘制图像float originalImageWidth = pdImage.getWidth();float originalImageHeight = pdImage.getHeight();// 初始化缩放比例float scale = 1.0f;// 判断是否需要缩放图片if (originalImageWidth > pageWidth || originalImageHeight > pageHeight) {// 计算宽度和高度的缩放比例,取较小值float widthScale = pageWidth / originalImageWidth;float heightScale = pageHeight / originalImageHeight;scale = Math.min(widthScale, heightScale);}// 计算缩放后的图片宽度和高度float scaledImageWidth = originalImageWidth * scale;float scaledImageHeight = originalImageHeight * scale;// 计算图片在页面中居中绘制的位置float x = (pageWidth - scaledImageWidth) / 2;float y = (pageHeight - scaledImageHeight) / 2;// 绘制缩放后的图片到PDF页面contentStream.drawImage(pdImage, x, y, scaledImageWidth, scaledImageHeight);// 关闭内容流contentStream.close();// 将PDF文档写入到字节数组中ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream();pdfDoc.save(pdfOutputStream);// 关闭PDF文档pdfDoc.close();// 删除临时文件tempFile.delete();// 创建代表PDF的MultipartFileMultipartFile pdfFile = new MockMultipartFile("converted12.pdf", "converted12.pdf", "application/pdf", pdfOutputStream.toByteArray());saveFileToLocalDisk(pdfFile, "D:/");return pdfFile;}/*** 将MultipartFile file文件保存到本地磁盘* @param file* @param directoryPath* @throws IOException*/public void saveFileToLocalDisk(MultipartFile file, String directoryPath) throws IOException {// 获取文件名String fileName = file.getOriginalFilename();// 创建目标文件File targetFile = new File(directoryPath + File.separator + fileName);// 将文件内容写入目标文件try (FileOutputStream outputStream = new FileOutputStream(targetFile)) {outputStream.write(file.getBytes());} catch (IOException e) {// 处理异常e.printStackTrace();throw e;}}

MockMultipartFile类

package com.jiuzhu.server.common;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;public class MockMultipartFile implements MultipartFile {private final String name;private String originalFilename;private String contentType;private final byte[] content;/*** Create a new MultipartFileDto with the given content.** @param name    the name of the file* @param content the content of the file*/public MockMultipartFile(String name, byte[] content) {this(name, "", null, content);}/*** Create a new MultipartFileDto with the given content.** @param name          the name of the file* @param contentStream the content of the file as stream* @throws IOException if reading from the stream failed*/public MockMultipartFile(String name, InputStream contentStream) throws IOException {this(name, "", null, FileCopyUtils.copyToByteArray(contentStream));}/*** Create a new MultipartFileDto with the given content.** @param name             the name of the file* @param originalFilename the original filename (as on the client's machine)* @param contentType      the content type (if known)* @param content          the content of the file*/public MockMultipartFile(String name, String originalFilename, String contentType, byte[] content) {this.name = name;this.originalFilename = (originalFilename != null ? originalFilename : "");this.contentType = contentType;this.content = (content != null ? content : new byte[0]);}/*** Create a new MultipartFileDto with the given content.** @param name             the name of the file* @param originalFilename the original filename (as on the client's machine)* @param contentType      the content type (if known)* @param contentStream    the content of the file as stream* @throws IOException if reading from the stream failed*/public MockMultipartFile(String name, String originalFilename, String contentType, InputStream contentStream)throws IOException {this(name, originalFilename, contentType, FileCopyUtils.copyToByteArray(contentStream));}@Overridepublic String getName() {return this.name;}@Overridepublic String getOriginalFilename() {return this.originalFilename;}@Overridepublic String getContentType() {return this.contentType;}@Overridepublic boolean isEmpty() {return (this.content.length == 0);}@Overridepublic long getSize() {return this.content.length;}@Overridepublic byte[] getBytes() throws IOException {return this.content;}@Overridepublic InputStream getInputStream() throws IOException {return new ByteArrayInputStream(this.content);}@Overridepublic void transferTo(File dest) throws IOException, IllegalStateException {FileCopyUtils.copy(this.content, dest);}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/831219.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux的基础IO:文件描述符 重定向本质

目录 前言 文件操作的系统调用接口 open函数 close函数 write函数 read函数 注意事项 文件描述符-fd 小补充 重定向 文件描述符的分配原则 系统调用接口-dup2 缓冲区 缓冲区的刷新策略 对于“2”的理解 小补充 前言 在Linux中一切皆文件&#xff0c;打开文件…

Leetcode 108.将有序数组转换为二叉搜索树

题目描述 给你一个整数数组 nums &#xff0c;其中元素已经按 升序 排列&#xff0c;请你将其转换为一棵 平衡 二叉搜索树。 示例 1&#xff1a; 输入&#xff1a;nums [-10,-3,0,5,9] 输出&#xff1a;[0,-3,9,-10,null,5] 解释&#xff1a;[0,-10,5,null,-3,null,9] 也将被…

改变 centos yum源 repo

centos 使用自带的 repo 源 速度慢&#xff0c;可以改为国内的&#xff0c;需要改两个地方 centos7.repo CentOS-Base.repo 首先备份/etc/yum.repos.d/CentOS-Base.repo mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup下载对应版本repo文件…

ICMP详解

3 ICMP ICMP&#xff08;Internet Control Message Protocol&#xff0c;因特网控制报文协议&#xff09;是一个差错报告机制&#xff0c;是TCP/IP协议簇中的一个重要子协议&#xff0c;通常被IP层或更高层协议&#xff08;TCP或UDP&#xff09;使用&#xff0c;属于网络层协议…

Uniapp好看登录注册页面

个人介绍 hello hello~ &#xff0c;这里是 code袁~&#x1f496;&#x1f496; &#xff0c;欢迎大家点赞&#x1f973;&#x1f973;关注&#x1f4a5;&#x1f4a5;收藏&#x1f339;&#x1f339;&#x1f339; &#x1f981;作者简介&#xff1a;一名喜欢分享和记录学习的…

4G+北斗太阳能定位终端:一键报警+倾覆报警 双重保障船舶安全

海上作业环境复杂多变&#xff0c;海上航行充满了各种不确定性和风险&#xff0c;安全事故时有发生&#xff0c;因此海上安全与应急响应一直是渔业和海运行业关注的重点。为了提高海上安全保障水平&#xff0c;4G北斗太阳能定位终端应运而生&#xff0c;它集成了一键报警和倾覆…

Edge浏览器新特性深度解析,写作ai免费软件

首先&#xff0c;这篇文章是基于笔尖AI写作进行文章创作的&#xff0c;喜欢的宝子&#xff0c;也可以去体验下&#xff0c;解放双手&#xff0c;上班直接摸鱼~ 按照惯例&#xff0c;先介绍下这款笔尖AI写作&#xff0c;宝子也可以直接下滑跳过看正文~ 笔尖Ai写作&#xff1a;…

【数据结构】:链表的带环问题

&#x1f381;个人主页&#xff1a;我们的五年 &#x1f50d;系列专栏&#xff1a;数据结构 &#x1f337;追光的人&#xff0c;终会万丈光芒 前言&#xff1a; 链表的带环问题在链表中是一类比较难的问题&#xff0c;它对我们的思维有一个比较高的要求&#xff0c;但是这一类…

AI大模型探索之路-训练篇10:大语言模型Transformer库-Tokenizer组件实践

系列篇章&#x1f4a5; AI大模型探索之路-训练篇1&#xff1a;大语言模型微调基础认知 AI大模型探索之路-训练篇2&#xff1a;大语言模型预训练基础认知 AI大模型探索之路-训练篇3&#xff1a;大语言模型全景解读 AI大模型探索之路-训练篇4&#xff1a;大语言模型训练数据集概…

DS:顺序表、单链表的相关OJ题训练

欢迎各位来到 Harper.Lee 的学习小世界&#xff01; 博主主页传送门&#xff1a;Harper.Lee的博客主页 想要一起进步的uu可以来后台找我交流哦&#xff01; 在DS&#xff1a;单链表的实现 和 DS&#xff1a;顺序表的实现这两篇文章中&#xff0c;我详细介绍了顺序表和单链表的…

使用LinkAI创建AI智能体,并快速接入到微信/企微/公众号/钉钉/飞书

​ LinkAI 作为企业级一站式AI Agent 智能体搭建与接入平台&#xff0c;不仅为用户和客户提供能够快速搭建具备行业知识和个性化设定的 AI 智能体的能力&#xff1b;还基于企业级场景提供丰富的应用接入能力&#xff0c;让智能体不再是“玩具”&#xff0c;而是真正能够落地应用…

PHP的数组练习实验

实 验 目 的 掌握索引和关联数组&#xff0c;以及下标和元素概念&#xff1b; 掌握数组创建、初始化&#xff0c;以及元素添加、删除、修改操作&#xff1b; 掌握foreach作用、语法、执行过程和使用&#xff1b; 能应用数组输出表格和数据。 任务1&#xff1a;使用一维索引数…

uniapp0基础编写安卓原生插件和调用第三方jar包和编写语音播报插件之使用jar包插件

前言 如果你不会编写安卓插件,你可以先看看我之前零基础的文章(uniapp0基础编写安卓原生插件和调用第三方jar包和编写语音播报插件之零基础编写安卓插件), 我们使用第三方包,jar包编写安卓插件 开始 把依赖包,放到某个模块的/libs目录(myTestPlug/libs) 还要到build…

R语言的学习—5—多元数据直观表示

1、数据读取 ## 数据整理 d3.1read.xlsx(adstats.xlsx,d3.1,rowNamesT);d3.1 #读取adstats.xlsx表格d3.1数据 barplot(apply(d3.1,1,mean)) #按行做均值条形图 barplot(apply(d3.1,1,mean),las3) barplot(apply(d3.1,2,mean)) #按列做均值图条形图 barplot(a…

C语言数据结构 ---- 单链表实现通讯录

今日备忘录: "折磨我们的往往是想象, 而不是现实." 目录 1. 前言2. 通讯录的功能3. 通讯录的实现思路5. 效果展示6. 完整代码7. 总结 正文开始 1. 前言 顺表实现通讯录: 点击~ 顺序表实现通讯录 在日常生活中&#xff0c;我们经常需要记录和管理大量的联系人信息&…

【研发管理】产品经理知识体系-组合管理

导读&#xff1a;新产品开发的组合管理是一个重要的过程&#xff0c;它涉及到对一系列新产品开发项目进行策略性选择、优先级排序、资源分配和监控。这个过程旨在确保企业能够最大化地利用有限的资源&#xff0c;以实现其战略目标。 目录 1、组合管理、五大目标 2、组合管理的…

第74天:漏洞发现-Web框架中间件插件BurpSuite浏览器被动主动探针

目录 思维导图 前置知识 案例一&#xff1a;浏览器插件-辅助&资产&漏洞库-Hack-Tools&Fofa_view&Pentestkit 案例二&#xff1a; BurpSuite 插件-被动&特定扫描-Fiora&Fastjson&Shiro&Log4j 思维导图 前置知识 目标&#xff1a; 1. 用…

基于springboot实现公司日常考勤系统项目【项目源码+论文说明】

基于springboot实现公司日常考勤系统演示 摘要 目前社会当中主要特征就是对于信息的传播比较快和信息内容的安全问题&#xff0c;原本进行办公的类型都耗费了很多的资源、传播的速度也是相对较慢、准确性不高等许多的不足。这个系统就是运用计算机软件来完成对于企业当中出勤率…

数据结构-链表OJ

1.删除链表中等于给定值 val 的所有结点。 . - 力扣&#xff08;LeetCode&#xff09; 思路一&#xff1a;遍历原链表&#xff0c;将值为val的节点释放掉 思路二&#xff1a;创建一个新链表&#xff0c;将值不为val的节点尾插到新链表中 /*** Definition for singly-linked …

2024年五一数学建模竞赛C题论文首发

基于随机森林的煤矿深部开采冲击地压危险预测 摘要 煤炭作为中国重要的能源和工业原料&#xff0c;其开采活动对国家经济的稳定与发展起着至关重要的作用。本文将使用题目给出的数据探索更为高效的数据分析方法和更先进的监测设备&#xff0c;以提高预警系统的准确性和可靠性…