如何将base64转换为pdf?

22

如何将一个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();
        }
    }

以上代码有效。


3
编辑1中的代码进行编码,而非解码。 - Henry
1
谢谢,你发现得真好。现在它能用了。 - Noman Arain
3个回答

32
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编码的字符串。


6
要将文件保存在/storage/emulated/0/Download中,请将DOWNLOADS_FOLDER更改为Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" - alditis

1
这段代码可能对您有帮助。我已经执行了附加的代码,它完美地运行。
public static GetFilePathAndStatus getFileFromBase64AndSaveInSDCard(String base64, String filename,String extension){
    GetFilePathAndStatus getFilePathAndStatus = new GetFilePathAndStatus();
    try {
        byte[] pdfAsBytes = Base64.decode(base64, 0);
        FileOutputStream os;
        os = new FileOutputStream(getReportPath(filename,extension), false);
        os.write(pdfAsBytes);
        os.flush();
        os.close();
        getFilePathAndStatus.filStatus = true;
        getFilePathAndStatus.filePath = getReportPath(filename,extension);
        return getFilePathAndStatus;
    } catch (IOException e) {
        e.printStackTrace();
        getFilePathAndStatus.filStatus = false;
        getFilePathAndStatus.filePath = getReportPath(filename,extension);
        return getFilePathAndStatus;
    }
}

public static String getReportPath(String filename,String extension) {
    File file = new File(Environment.getExternalStorageDirectory().getPath(), "ParentFolder/Report");
    if (!file.exists()) {
        file.mkdirs();
    }
    String uriSting = (file.getAbsolutePath() + "/" + filename + "."+extension);
    return uriSting;

}
public static class GetFilePathAndStatus{
    public boolean filStatus;
    public String filePath;

}

0

这个解决方案在Kotlin上对我有效

private fun setPdfDownload(bill: BillDataPdfOutput){
    if (bill.data != null) {

        val file = File(getFilePath("pdf_name"))

        try {
            FileOutputStream(file).use { fos ->
                val decoder = Base64.getDecoder().decode(bill.data)
                fos.write(decoder)
                Toast.makeText(this, "downloading success", Toast.LENGTH_LONG).show()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }


    }else {
        Log.v("PDF", "not download " + bill.message)
    }
}

fun getFilePath(filename: String): String {
    val file =
        File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).path)
    if (!file.exists()) {
        file.mkdirs()
    }
    return file.absolutePath.toString() + "/" + filename + ".pdf"
}

你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接