所以我收到来自服务的响应,该服务是String
中pdf文件的字节数组表示,如下所示:
response.pdfStream = "JVBERi0xLjQKJcfsj6IKNSAwIG9iago8PC9MZW5ndGggNiAwIFIvRmlsdGVyIC9GbGF0ZURlY29kZT4+CnN0cmVhbQp4nK1aS3MbxxG+45Qql+9zcQlIEat57wxzAgJIcviQTYCqKGIOKwEWN3hJIKgU+Wt88U9I/kKuOflk6OqrTz4RrHyzu7MASCzHUkypCtBOT3dPT39fdy/1ntBIGkLdH//lzaT2+CQmby9q7wnjUmUPxXrJkM6s9u3mIuOZRLZqd68ylS8zunudx8U6q9Bui3W+e12xYl3sXtcPuxerB5dN/OCytQ+fnbGH13kgduJh75h82D2mfPBkhUDso6cqBIwICFj1sACncUCA2YCACDjJZcBJrkJO6pCTcchJG3BS0ICTggWcFDzgpBABJ4UKOalDTsYhJ03ISRtwUrKAk5IHnJQi4KSUASelCjkZAo4MAUeGgKNCwFEh4KgQcFQIOCoEHBUCjgoBR4WAo0PA0SHg6BBwdAg4OgQcHQKODgFHh4CjQ8CJQ8CJQ8CJQ8CJQ8CJQ8CJQ8CJQ8CJQ8AxIeCYEHBMCDgmBBwTAo4JAceEgGNCwLEh4NgQcGwIODYEHBsCjg0Bx4aAY0PAsSHgMBpCDqMh6DAawg6jIfAwGkIPo8GGj..."
我需要将其转换为绝对字节数组,然后创建pdf文件并打开它。
试过这个:
byte[] pdfStream = response.pdfStream.getBytes(Charsets.UTF_8);
InputStream inputStream = new ByteArrayInputStream(pdfStream);
File file = null;
try {
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
Logger.debug("createFile: "+file.getAbsolutePath());
OutputStream outputStream = new FileOutputStream(file);
IOUtils.copy(inputStream, outputStream);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
getMainActivity().startActivity(intent);
} catch (Exception e) {
Logger.printStackTrace(e);
}
答案 0 :(得分:3)
使用此代码片段,可以非常轻松地将Base64编码的字符串转换为pdf文件。 从input.txt文件中读取String。
public void convertInputFile() {
try {
convertToPDF("/home/input.txt");
} catch (IOException e) {
}
}
private void convertToPDF(String inputFilePath) throws IOException {
byte[] byteArray = Files.toByteArray(new File(inputFilePath));
byte[] bytes = Base64.decodeBase64(byteArray);
DataOutputStream os = new DataOutputStream(new FileOutputStream("/home/output.pdf"));
os.write(bytes);
os.close();
}