【发布时间】:2015-07-29 07:28:45
【问题描述】:
我整天都在用头撞墙。我有一个我们生成的 PDF 文件。 PDF 文件在 Acrobat 中看起来不错。
我需要用 base64 对文件进行编码。使用 Apache 编解码器库我这样做:
String base64buf = Base64.encodeBase64String( m_reportText.getBytes( "UTF-8" ) );
作为测试,我将 base64buf 写入文件:
Files.write( new File( "report.b64" ).toPath(), base64buf.getBytes( "UTF-8") );
然后我把它转换回来,看看它是否工作:
String encodedName = "report.b64";
String decodedName = "report.pdf";
// Read original file.
byte[] encodedBuffer = Files.readAllBytes( new File( encodedName ).toPath() );
// Decode
byte[] decodedBuffer = Base64.decodeBase64( encodedBuffer );
// Write out decodedBuffer.
FileOutputStream outputStream = new FileOutputStream( decodedName );
outputStream.write( decodedBuffer );
outputStream.close();
我在 Acrobat 中打开 report.pdf,它是一个空白文档。它的页数正确(全部为空白)。
我在这里错过了什么?
【问题讨论】:
-
当我认为
m_reportText是一个包含PDF 的成员变量并且这个成员变量是String时,我是否正确解释了您的代码?如果是这种情况,您无论如何都会遇到麻烦,因为 PDF 文件是二进制文件,而不是文本文件(即使它们部分看起来是文本文件)。而且你对该变量内容的 UTF-8 编码(不是 base64 字符串,虽然)会破坏它。
标签: java pdf base64 apache-commons-codec