简体   繁体   English

将PDF文件的内容转换为Java中的Base 64,反之亦然

[英]PDF file content to Base 64 and vice versa in Java

I need to convert PDF content to Base64 and use that as a String. 我需要将PDF内容转换为Base64并将其用作字符串。 When I use the below program to test the out.pdf becomes blank. 当我使用以下程序测试out.pdf时,将为空白。

    byte[] pdfRawData =  FileUtils.readFileToByteArray(new File("C:\\in.pdf")) ;
    String pdfStr = new String(pdfRawData);

//My data is available in the form of String

    BASE64Encoder encoder = new BASE64Encoder();
    String encodedPdf = encoder.encode(pdfStr.getBytes());
    System.out.println(encodedPdf);


// Decode the encoded content to test


    BASE64Decoder decoder = new BASE64Decoder();        
    FileUtils.writeByteArrayToFile(new File("C:\\out.pdf") , decoder.decodeBuffer(encodedPdf));

Can anyone please help me? 谁能帮帮我吗?

Why are you doing: 你为什么这么做:

String pdfStr = new String(pdfRawData);

instead of passing pdfRawData to the encoder? 而不是将pdfRawData传递给编码器?

Doing so lead to lots of encoding issue, as you don't specify the encoding of the byte array to use to build the string (it will use platform default). 这样做会导致很多编码问题,因为您没有指定用于构建字符串的字节数组的编码(它将使用平台默认值)。 And this is clearly redondant (byte array -> string -> byte array) 这显然是redondant(字节数组->字符串->字节数组)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM