Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary data in String representation to PDF file

So I'm receiving a response from a service which is a byte array representation of pdf file in String like below:

response.pdfStream = "JVBERi0xLjQKJcfsj6IKNSAwIG9iago8PC9MZW5ndGggNiAwIFIvRmlsdGVyIC9GbGF0ZURlY29kZT4+CnN0cmVhbQp4nK1aS3MbxxG+45Qql+9zcQlIEat57wxzAgJIcviQTYCqKGIOKwEWN3hJIKgU+Wt88U9I/kKuOflk6OqrTz4RrHyzu7MASCzHUkypCtBOT3dPT39fdy/1ntBIGkLdH//lzaT2+CQmby9q7wnjUmUPxXrJkM6s9u3mIuOZRLZqd68ylS8zunudx8U6q9Bui3W+e12xYl3sXtcPuxerB5dN/OCytQ+fnbGH13kgduJh75h82D2mfPBkhUDso6cqBIwICFj1sACncUCA2YCACDjJZcBJrkJO6pCTcchJG3BS0ICTggWcFDzgpBABJ4UKOalDTsYhJ03ISRtwUrKAk5IHnJQi4KSUASelCjkZAo4MAUeGgKNCwFEh4KgQcFQIOCoEHBUCjgoBR4WAo0PA0SHg6BBwdAg4OgQcHQKODgFHh4CjQ8CJQ8CJQ8CJQ8CJQ8CJQ8CJQ8CJQ8CJQ8AxIeCYEHBMCDgmBBwTAo4JAceEgGNCwLEh4NgQcGwIODYEHBsCjg0Bx4aAY0PAsSHgMBpCDqMh6DAawg6jIfAwGkIPo8GGj..."

I need to convert this to absolute byte array and then create pdf file with it to open.

Tried this:

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);
}
like image 280
Canberk Ozcelik Avatar asked Nov 22 '16 08:11

Canberk Ozcelik


1 Answers

With this code snippet it was very easy to convert a Base64 encoded String to a pdf-File. The String is read from the input.txt file.

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();
}
like image 53
Daniel P. Avatar answered Oct 12 '22 10:10

Daniel P.