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

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.lryc.cn/news/2378812.html

相关文章:

  • 开源RTOS(实时操作系统):nuttx 编译
  • python打包exe报错:处理文件时错误:Excel xlsx file; not supported
  • VUE3 -综合实践(Mock+Axios+ElementPlus)
  • NDS3211HV单路H.264/HEVC/HD视频编码器
  • LeetCode热题100--206.反转链表--简单
  • 来一个复古的技术FTP
  • OpenCV CUDA模块中矩阵操作------分布统计类
  • OpenWebUI新突破,MCPO框架解锁MCP工具新玩法
  • go.mod关于go版本异常的处理
  • TRTC实时对话式AI解决方案,助力人机语音交互极致体验
  • Linux安全篇 --firewalld
  • 系分论文《论系统需求分析方法及应用》
  • LIIGO ❤️ RUST: 12 YEARS
  • SQL、Oracle 和 SQL Server 的比较与分析
  • Trivy:让你时刻掌控的开源安全扫描器
  • LlamaIndex 第八篇 MilvusVectorStore
  • 2022河南CCPC(前四题)
  • 谷歌浏览器(Google Chrome)136.0.7103.93便携增强版|Win中文|安装教程
  • 高可用消息队列实战:AWS SQS 在分布式系统中的核心解决方案
  • 「Mac畅玩AIGC与多模态41」开发篇36 - 用 ArkTS 构建聚合搜索前端页面
  • springCloud/Alibaba常用中间件之Seata分布式事务
  • Datawhale FastAPI Web框架5月第1次笔记
  • 操作系统:os概述
  • LLaMA-Factory:环境准备
  • ArrayList-集合使用
  • 一分钟用 MCP 上线一个 贪吃蛇 小游戏(CodeBuddy版)
  • pytorch小记(二十二):全面解读 PyTorch 的 `torch.cumprod`——累积乘积详解与实战示例
  • TTS:F5-TTS 带有 ConvNeXt V2 的扩散变换器
  • 强化学习笔记(一)基本概念
  • 大型语言模型中的QKV与多头注意力机制解析