• Java如何实现pdf转base64以及怎么反转?


    问题需求

    今天在做发送邮件功能的时候,发现邮件的附件部分,比如pdf文档,要求先把pdf转为base64,邮件才会发送。那接下来就先看看Java 如何把 pdf文档转为base64。

    两种方式,一种是通过插件 jar 包的方式引入,另外一种则是 通过原生的 文件流来读取pdf 并转为 byte 字节。

    jar包引入

    <dependency>
        <groupId>org.apache.pdfboxgroupId>
        <artifactId>fontboxartifactId>
        <version>2.0.1version>
    dependency>
    
    <dependency>
        <groupId>org.apache.pdfboxgroupId>
        <artifactId>pdfboxartifactId>
        <version>2.0.1version>
    dependency>
    
    代码测试
    import org.apache.pdfbox.pdmodel.PDDocument;
    import org.apache.pdfbox.io.RandomAccessBuffer;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.util.Base64;
     
    public class PDFToBase64 {
        public static String convertPDFToBase64(Path pdfPath) throws IOException {
            try (PDDocument document = PDDocument.load(pdfPath.toFile())) {
                // 使用ByteArrayOutputStream来获取PDF的字节内容
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                document.save(outputStream);
                byte[] pdfBytes = outputStream.toByteArray();
     
                // 将字节转换为Base64字符串
                return Base64.getEncoder().encodeToString(pdfBytes);
            }
        }
     
        public static void main(String[] args) {
            try {
                Path pdfPath = Files.createTempFile("test", ".pdf");
                // 这里应该是你的PDF文件路径
                String base64String = convertPDFToBase64(pdfPath);
                System.out.println(base64String);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    在这里插入图片描述

    原生 InputStream 实现
    
    import java.io.ByteArrayOutputStream;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
     try {
                URL obj = new URL(url);
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    
                // 添加请求头,如有必要
                con.setRequestMethod("GET");
                con.setRequestProperty("Accept", "application/pdf");
    
                int responseCode = con.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) { // 200
                    InputStream inputStream = con.getInputStream();
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    
                    byte[] buffer = new byte[4096];
                    int n;
                    while ((n = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, n);
                    }
    
                    byte[] pdfBytes = outputStream.toByteArray();
                    String base64Encoded = Base64.getEncoder().encodeToString(pdfBytes);
    
                    log.info("base64==" + base64Encoded);
                    return base64Encoded;
    
                } else {
                    System.out.println("GET request not worked");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    

    在这里插入图片描述

  • 相关阅读:
    ESP8266-Arduino编程实例-BME280环境传感器驱动
    【Axure高保真原型】3D圆柱图_中继器版
    vue中的mixin混入
    企业数据分析的维度一般有哪些?
    [笔记]vue从入门到入坟《四》HBuilderX Vue开发
    【电商】电商后台设计—促销模块(下)
    Java数据审计工具:Envers and JaVers比较
    【C语言 | 预处理】C语言预处理详解(一) —— #define、#under、#if、#else、#elif、#endif、#include、#error
    贪心算法-Huffman算法
    gitlab的安装与迁移
  • 原文地址:https://blog.csdn.net/weixin_44427181/article/details/139421982