如何将Pdf转换为base64和编码/解码

DKK*_*KKs 9 java pdf base64 encode decode

好吧,我有一些pdf需要通过base64encoder转换为base64.

最后,我使用解码器转换回pdf格式,但我的内容丢失了.

我的代码:

byte[] input_file = Files.readAllBytes(Paths.get("C:\\user\\Desktop\\dir1\\dir2\\test3.pdf"));
    byte[] encodedBytes = Base64.getEncoder().encode(input_file);

    String pdfInBase64 = new String(encodedBytes);
    String originalString = new String(Base64.getDecoder().decode(encodedBytes));

    System.out.println("originalString : " + originalString);

    FileOutputStream fos = new FileOutputStream("C:\\user\\Desktop\\dir1\\dir2\\newtest3.pdf");
    fos.write(originalString.getBytes());
    fos.flush();
    fos.close();
Run Code Online (Sandbox Code Playgroud)

结果:

编码:https://pastebin.com/fnMACZzH

在base64encode之前

解码后

谢谢

Aji*_*man 11

您可以解码base64编码的String并将其传递byte[]FileOutputStreamwrite方法来解决此问题.

        String filePath = "C:\\Users\\xyz\\Desktop\\";
        String originalFileName = "96172560100_copy2.pdf";
        String newFileName = "test.pdf";

        byte[] input_file = Files.readAllBytes(Paths.get(filePath+originalFileName));

        byte[] encodedBytes = Base64.getEncoder().encode(input_file);
        String encodedString =  new String(encodedBytes);
        byte[] decodedBytes = Base64.getDecoder().decode(encodedString.getBytes());

        FileOutputStream fos = new FileOutputStream(filePath+newFileName);
        fos.write(decodedBytes);
        fos.flush();
        fos.close();
Run Code Online (Sandbox Code Playgroud)