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

PDF Base64格式字符串转换为PDF文件临时文件

需求描述:

        在对接电子病历系统与河北CA,进行免密文件签章的时候,两者系统入参不同,前者是pdf文件,base64格式;后者要求File类型的PDF文件。

        在业务中间层开发时,则需要接收EMR侧提供的base64格式字符串,并将其转化为临时PDF文件(支持指定位置,若无则默认存于当前用户下的临时文件目录),以供CA侧进行文件签。

注意事项:

  • 资源管理:ByteArrayInputStream 和 FileOutputStream 都是需要显式关闭的资源。可以使用 try-with-resources 来自动管理这些资源,避免资源泄漏。
  • Base64 编码与解码优化(优化点,考虑病历文件最多10M左右,则无需考虑此问题):Base64.getEncoder().encodeToString() 和 Base64.getDecoder().decode() 可以处理较大的文件,但对于大文件,使用流的方式进行分块处理会更加高效,避免内存溢出。

代码实现逻辑:

  1. 将 PDF 文件转换为 Base64 编码字符串:

    • convertPdfToBase64()方法读取文件内容并将其转换为 Base64 字符串。
  2. 将 Base64 字符串转换回 PDF 文件:

    • convertBase64ToPdfInMemory()方法将 Base64 字符串解码,并返回 ByteArrayInputStream,其中包含转换后的 PDF 数据。
  3. 将内存中的 PDF 写入临时文件:

    • createTempFileFromStream()方法接受一个 ByteArrayInputStream,并将其中的字节数据写入到临时文件。
  4. 删除临时文件:

    • 文件处理完毕后,程序删除临时文件。
package com.bsoft.server.utils;import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;public class PdfToBase64Converter {public static void main(String[] args) {String pdfFilePath = "C:\\Users\\19079\\Desktop\\123.pdf"; // 替换为你的输入PDF文件路径String tempDirPath = "C:\\Users\\19079\\Desktop"; // 替换为你想要的临时目录路径,留空则使用默认临时目录try {// 将 PDF 转换为 Base64String base64String = convertPdfToBase64(pdfFilePath);System.out.println("Base64 Encoded PDF:");System.out.println(base64String);// 将 Base64 转换回内存中的 PDFByteArrayInputStream pdfInMemory = convertBase64ToPdfInMemory(base64String);// 将内存中的 PDF 写入临时文件File tempFile = createTempFileFromStream(pdfInMemory, tempDirPath);System.out.println("临时 PDF 文件创建位置: " + tempFile.getAbsolutePath());// 现在,您可以使用 tempFile 进行进一步处理System.out.println("PDF 文件大小: " + tempFile.length() + " bytes");// TODO 根据需要处理文件...// 处理后删除临时文件if (tempFile.delete()) {System.out.println("已成功删除临时文件。");} else {System.out.println("无法删除临时文件。");}} catch (IOException e) {System.err.println("IOException occurred: " + e.getMessage());e.printStackTrace();}}public static String convertPdfToBase64(String filePath) throws IOException {byte[] fileContent = Files.readAllBytes(Paths.get(filePath));return Base64.getEncoder().encodeToString(fileContent);}public static ByteArrayInputStream convertBase64ToPdfInMemory(String base64String) throws IOException {byte[] decodedBytes = Base64.getDecoder().decode(base64String);return new ByteArrayInputStream(decodedBytes);}public static File createTempFileFromStream(ByteArrayInputStream inputStream, String dirPath) throws IOException {File tempDir = (dirPath != null && !dirPath.isEmpty()) ? new File(dirPath) : new File(System.getProperty("java.io.tmpdir"));if (!tempDir.exists()) {throw new IOException("指定目录不存在: " + dirPath);}// 创建临时文件File tempFile = Files.createTempFile(tempDir.toPath(), "temp", ".pdf").toFile();// 确保 JVM 退出时删除该文件tempFile.deleteOnExit();// 使用 try-with-resources 自动关闭资源try (FileOutputStream fos = new FileOutputStream(tempFile)) {byte[] buffer = new byte[1024];int bytesRead;while ((bytesRead = inputStream.read(buffer)) != -1) {fos.write(buffer, 0, bytesRead);}}return tempFile;}
}

http://www.dtcms.com/a/189921.html

相关文章:

  • 具身智能梳理以及展望
  • 读入csv文件写入MySQL
  • 《AI大模型应知应会100篇》第64篇:构建你的第一个大模型 Chatbot
  • 鸿蒙OSUniApp 开发实时聊天页面的最佳实践与实现#三方框架 #Uniapp
  • FFmpeg 与 C++ 构建音视频处理全链路实战(五)—— 音视频编码与封装
  • 【MySQL 基础篇】深入解析MySQL逻辑架构与查询执行流程
  • 苹果处理器“仿生“命名背后的营销策略与技术创新
  • 最短路和拓扑排序知识点
  • 零基础学Java——第十一章:实战项目 - 桌面应用开发(JavaFX入门)
  • How Sam‘s Club nudge customers into buying more
  • 【IPMV】图像处理与机器视觉:Lec11 Keypoint Features and Corners
  • 开源 Web Shell 工具
  • C语言学习之文件操作
  • zookeeper本地部署
  • 12-串口外设
  • Flutter到HarmonyOS Next 的跨越:memory_info库的鸿蒙适配之旅
  • 本地测试远程DM达梦数据库连接(使用DBeaver)
  • 砷化镓太阳能电池:开启多元领域能源新篇
  • 印刷业直角坐标型码垛机器人系统设计与应用研究
  • sql server 2019 将单用户状态修改为多用户状态
  • C++学习之打车软件git版本控制
  • React Native矢量图标全攻略:从入门到自定义iconfont的高级玩法
  • 【AAAI 2025】 Local Conditional Controlling for Text-to-Image Diffusion Models
  • 算法每日刷题 Day6 5.14:leetcode数组1道题,用时30min,明天按灵茶山艾府题单开刷,感觉数组不应该单算
  • hbase shell的常用命令
  • Kubernetes控制平面组件:Kubelet详解(三):CRI 容器运行时接口层
  • 【unity游戏开发——编辑器扩展】使用EditorGUI的EditorGUILayout绘制工具类在自定义编辑器窗口绘制各种UI控件
  • iOS Safari调试教程
  • DeepSeek:AI助力高效工作与智能管理
  • 作业帮Android面试题及参考答案