java 是否可以从 base64 字符串创建 pdf 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34890501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to create a pdf file from base64 string?
提问by Eleven
I have a hl7 file which contains a base64 string derived from an encoded pdf.
我有一个 hl7 文件,其中包含从编码的 pdf 派生的 base64 字符串。
Is it possible to recreate a pdf from that base64?
是否可以从该 base64 重新创建 pdf?
pdf to base64 --> ok
----------------------------
base64 to pdf --> is this possible?
回答by Jorge Casiano
It′s possible. You can use sun.misc.BASE64Decoder.
这是可能的。您可以使用 sun.misc.BASE64Decoder。
Example:
例子:
import java.io.*;
import sun.misc.BASE64Decoder;
/**
* Kax7ux
*
*/
public class App
{
public static void main( String[] args )
{
String encodedBytes = "yourStringBase64";
try {
BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes;
FileOutputStream fop;
decodedBytes = new BASE64Decoder().decodeBuffer(encodedBytes);
File file = new File("path/file.pdf");
fop = new FileOutputStream(file);
fop.write(decodedBytes);
fop.flush();
fop.close();
System.out.println("Created");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
回答by Manu
@Clem You can easy use the Base64class from java.util
@Clem 您可以轻松使用java.util 中的Base64类
import java.util.Base64;
public class App
{
public static void main( String[] args )
{
String pdfAsArrayByte = "JVBERi/8KNyAwIG9iago8PAovVHlwZS....";
// Decode the Base64 arrayByte to PDF file
DataSource source = new ByteArrayDataSource(Base64.getDecoder().decode(pdfAsArrayByte),"application/pdf");
// The ,source, instance is now a true PDF file
}
}