gpt4 book ai didi

android - 如何将base64转换为pdf?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:57:13 25 4
gpt4 key购买 nike

给定一个 base64 输入,我如何在 Android 中将其转换为 PDF 文件?

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
// Get the PDF file to encode it into Base64
File file = new File("/mnt/sdcard/download/Base64.pdf");
try {
// Files is from Guava library
Files.toByteArray(file);
// Encoded into Base64
byte[] temp = Base64.encode(Files.toByteArray(file), Base64.DEFAULT);
// For testing purposes, wrote the encoded string to file
writeToFile(Base64.encodeToString(temp, Base64.DEFAULT).toString());

} catch (IOException e) {
Log.d(tag, "File.toByteArray() error");
e.printStackTrace();
}
}

我能够使用 http://www.webutils.pl/index.php?idx=base64测试 PDF 文件是否被正确编码。但我希望自己能够将 base64 解码回 PDF。我该怎么做?

编辑 1

按照 Saneesh CS 的建议尝试了以下代码

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
// Get the PDF file to encode it into Base64
File file = new File("/mnt/sdcard/download/Base64.pdf");
try {
// Files is from Guava library
Files.toByteArray(file);
// Encoded into Base64
byte[] temp = Base64.encode(Files.toByteArray(file), Base64.DEFAULT);
// Tried with the below line, but same result.
byte[] temp1 = Base64.encode(Files.toByteArray(file), 0);
// For testing purposes, wrote the encoded string to file
// writeToFile(Base64.encodeToString(temp, Base64.DEFAULT).toString());
final File dwldsPath = new File(Environment.getExternalStorageDirectory(), "test7.pdf");
byte[] pdfAsBytes = Base64.decode(temp, 0);
FileOutputStream os;
os = new FileOutputStream(dwldsPath, false);
os.write(pdfAsBytes);
os.flush();
os.close();
} catch (IOException e) {
Log.d(tag, "File.toByteArray() error");
e.printStackTrace();
}
}

以上代码有效。

最佳答案

final File dwldsPath = new File(DOWNLOADS_FOLDER + fileName + ".pdf");
byte[] pdfAsBytes = Base64.decode(txt, 0);
FileOutputStream os;
os = new FileOutputStream(dwldsPath, false);
os.write(pdfAsBytes);
os.flush();
os.close();

试试这段代码。 txt是base64编码的字符串。

关于android - 如何将base64转换为pdf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19957467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com