【问题标题】:How to Convert Pdf to base64 and Encode / Decode如何将 Pdf 转换为 base64 和编码/解码
【发布时间】:2018-08-29 04:10:24
【问题描述】:

好的,我有一些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();

结果:

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

Before base64encode

After decode

谢谢

【问题讨论】:

  • 如果您只是将encodedBytes 写入文件,而不是通过String 泵送它然后写入String 的字节,会发生什么情况?
  • 你不应该通过originalString。保留原始解码字节。
  • @LouisWasserman 哦,我明白了,谢谢 :)

标签: java pdf base64 decode encode


【解决方案1】:

您可以解码 base64 编码的字符串并将 byte[] 传递给 FileOutputStream 写入方法来解决此问题。

        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();

【讨论】:

    【解决方案2】:

    我使用过 Apache Commons 库。我用于测试此实用程序的版本是 commons-code-1.4.jar。 Base64 编解码器有多种用途。我需要的是在 Docusign eSignature 网络服务调用期间,其中附加的文件以 Base64 编码格式发送。

    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    import org.apache.commons.codec.binary.Base64;
    
    public class FileCodecBase64 {
    
        private static final boolean IS_CHUNKED = true;
    
        public static void main(String args[]) throws Exception {
    
            /* Encode a file and write the encoded output to a text file. */
            encode("C:/temp/something.pdf", "c:/temp/something-encoded.txt", IS_CHUNKED);
    
            /* Decode a file and write the decoded file to file system */
            decode("C:/temp/something-encoded.txt", "c:/temp/something-decoded.pdf");
        }
    
        /**
         * This method converts the content of a source file into Base64 encoded data and saves that to a target file.
         * If isChunked parameter is set to true, there is a hard wrap of the output  encoded text.
         */
        private static void encode(String sourceFile, String targetFile, boolean isChunked) throws Exception {
    
            byte[] base64EncodedData = Base64.encodeBase64(loadFileAsBytesArray(sourceFile), isChunked);
    
            writeByteArraysToFile(targetFile, base64EncodedData);
        }
    
        public static void decode(String sourceFile, String targetFile) throws Exception {
    
            byte[] decodedBytes = Base64.decodeBase64(loadFileAsBytesArray(sourceFile));
    
            writeByteArraysToFile(targetFile, decodedBytes);
        }
    
        /**
         * This method loads a file from file system and returns the byte array of the content.
         * 
         * @param fileName
         * @return
         * @throws Exception
         */
        public static byte[] loadFileAsBytesArray(String fileName) throws Exception {
    
            File file = new File(fileName);
            int length = (int) file.length();
            BufferedInputStream reader = new BufferedInputStream(new FileInputStream(file));
            byte[] bytes = new byte[length];
            reader.read(bytes, 0, length);
            reader.close();
            return bytes;
    
        }
    
        /**
         * This method writes byte array content into a file.
         * 
         * @param fileName
         * @param content
         * @throws IOException
         */
        public static void writeByteArraysToFile(String fileName, byte[] content) throws IOException {
    
            File file = new File(fileName);
            BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(file));
            writer.write(content);
            writer.flush();
            writer.close();
    
        }
    }
    

    我希望这个工作

    【讨论】:

      【解决方案3】:
      if (resultCode == RESULT_OK) {
      
       InputStream is = null;
      
        try 
      
      {
      
      is = getContentResolver().openInputStream(imageReturnedIntent.getData());
      
      } 
      
      catch (FileNotFoundException e) 
      {
      
       e.printStackTrace();
      
       }
      
       byte[] bytesArray = new byte[0];
      
      try {
      
        bytesArray = new byte[is.available()];
      
       } 
      catch (IOException e) {
      
       e.printStackTrace();
      
        }
      
        try
       {
      
        is.read(bytesArray);
      
      String d = Base64.encodeToString(bytesArray, android.util.Base64.DEFAULT);
      
      
                          } catch (IOException e) {
                              e.printStackTrace();
                          }
                      }
      

      【讨论】:

        【解决方案4】:
        import java.io.File;
        import java.io.FileOutputStream;
        import java.io.OutputStream;
        import java.nio.file.Files;
        import java.nio.file.Paths;
        import java.util.Base64;
        
        public class Base64Sample {
        
        public static void main(String... strings) throws Exception {
            String filePath = "/home/user/sample.pdf";
            File pdfFile = new File(filePath);
            byte[] encoded = Files.readAllBytes(Paths.get(pdfFile.getAbsolutePath()));
            Base64.Encoder enc = Base64.getEncoder();
            byte[] strenc = enc.encode(encoded);
            String encode = new String(strenc, "UTF-8");
            Base64.Decoder dec = Base64.getDecoder();
            byte[] strdec = dec.decode(encode);
            OutputStream out = new FileOutputStream("/home/user/out.pdf");
            out.write(strdec);
            out.close();
        }
          }
        

        【讨论】:

          【解决方案5】:

          我尝试了很多代码,然后在我尝试了下面的代码及其对我的工作之后。 此代码也适用于其他文件,例如 .png、.jpg、jpeg、.pdf 和 .doc 等...

          String base64 = Base64.encodeToString(getBytesFromUri(uri, requireContext()), Base64.NO_WRAP);
                                  
          
          public static byte[] getBytesFromUri(Uri uri, Context context) throws IOException {
                  InputStream iStream = context.getContentResolver().openInputStream(uri);
                  ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
                  int bufferSize = 1024;
                  byte[] buffer = new byte[bufferSize];
          
                  int len = 0;
                  while ((len = iStream.read(buffer)) != -1) {
                      byteBuffer.write(buffer, 0, len);
                  }
                  return byteBuffer.toByteArray();
              }
          

          希望对你有帮助!

          【讨论】:

            猜你喜欢
            • 2019-02-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-04-27
            • 1970-01-01
            • 1970-01-01
            • 2020-10-11
            • 2019-07-28
            相关资源
            最近更新 更多