The Android code is correct, but an error is reported when converting the Base64 string to pdf (solved)

Convert pdf core code

public static void base64StringToPdf(String base64Content,String filePath,Base64Listen base64Listen){
        if (TextUtils.isEmpty(base64Content)){  
            return;
        }
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            // 将base64编码的字符串解码成字节数组
            byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT);    //base64编码内容转换为字节数组:DEFAULT
            //创建一个将bytes作为其缓冲区的ByteArrayInputStream对象
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
            //创建从底层输入流中读取数据的缓冲输入流对象
            bis = new BufferedInputStream(byteInputStream);
            // 指定输出的文件
            File file = new File(filePath);
            File path = file.getParentFile();
            if(!path.exists()){
                path.mkdirs();
            }
            // 创建到指定文件的输出流
            fos = new FileOutputStream(file);
            // 为文件输出流对接缓冲输出流对象
            bos = new BufferedOutputStream(fos);
            byte[] buffer = new byte[1024];
            int length = bis.read(buffer);
            while(length != -1){
                bos.write(buffer, 0, length);
                length = bis.read(buffer);
            }
            // 刷新此输出流并强制写出所有缓冲的输出字节,必须这行代码,否则有可能有问题
            bos.flush();
            base64Listen.onSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            base64Listen.onFail(e.toString()+"");
        }finally{
            try {
                if (bis != null){
                    bis.close();
                }
                if (fos != null){
                    fos.close();
                }
                if (bos != null){
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                base64Listen.onFail(e.toString()+"");
            }

        }
    }

success failure interface

public interface Base64Listen{
        void onSuccess();
        void onFail(String hint);
    }

Reasons why base64 conversion fails

When you find that your code is fine, but it is unsuccessful, it is likely that the problem is caused by other reasons

  • There is a problem with the base64 data itself. The way to check it is to see if there is a "+" sign in the data returned by the interface;

Guess you like

Origin blog.csdn.net/piyangbo/article/details/127372386