pdf转base64字符串及base64字符串反转pdf

pdf转base64

复制代码
//转base64
    public  String fileToBase64() {
//        String imgFilePath = "C:\\Users\\zlf\\Desktop\\pdf\\042002200211_87910810.pdf";
        String imgFilePath = "C:\\Users\\zlf\\Desktop\\pdf\\【高德打车-38.65元-1个行程】高德打车电子行程单.pdf";
        String[] res = imgFilePath.split("\\.");
        String pos = res[res.length - 1];
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgFilePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String data1 = Base64.encodeBase64String(data);
        System.out.println(data1);
        return data1;
    }
复制代码

Base64转pdf

复制代码
//转pdf
    @Test
    public void sfad(){
        String s = this.fileToBase64();
        byte[] decode = Base64.decodeBase64(s);
        File file = new File("d:/file2.pdf");//pdf保存路径
        try {
            FileOutputStream fop =  new FileOutputStream(file);
            try {
                fop.write(decode);
                fop.flush();
                fop.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
复制代码

这里的Base64我用的commons-codec:1.15

可以用jdk1.8的base64,如下

复制代码
public static void main(String[] args) throws UnsupportedEncodingException {
    String string = "12345";
    System.out.println("old string: " + string);
    String base64 = Base64.getEncoder().encodeToString(string.getBytes("UTF-8"));
    System.out.println("base64 decode: " + base64);

    byte[] bytes = Base64.getDecoder().decode(base64);
    System.out.println("base64 encode: " + new String(bytes, "UTF-8"));
}
复制代码

 

posted @   凉了记忆  阅读(791)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示