Rafael Acurcio
Rafael Acurcio

Reputation: 43

Convert StringBuffer into PDF file

I'm working in this project where I receive from a webservice in the following form:

%PDF-1.5%����3 0 obj<</Length 1294 /Filter /FlateDecode>>streamx�uV�n#G��W�X,E����$d✂��e�A�Z��íe�P��܊E>���ӧ�~.��ql�v��)�~��;t�l6O��O�����.......

And I can't read this as a pdf. I have tried to insert those bytes into a pdf file, but it didn't work. I also tried to open using a webview...no success.

Here some of the code:

URL url = new URL(LINKTOWEBSERVICE); //Enter URL here
private StringBuffer response;
JSONObject jsonObject = new JSONObject();
jsonObject.put("_id", obj.getLogin());
jsonObject.put("senha", md5(obj.getPassword()));

String mensagem = jsonObject.toString();

//connection with server
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);

connection.setFixedLengthStreamingMode(mensagem.getBytes().length);
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");

//Opening connection
connection.connect();

//Sending data
OutputStream outputStream = new BufferedOutputStream(connection.getOutputStream());
outputStream.write(mensagem.getBytes());
outputStream.flush();

//Response
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
response = new StringBuffer();
String inputLine;
while ((inputLine = bufferedReader.readLine()) != null) {
   response.append(inputLine);
                }

bufferedReader.close();

.

public File createPDF(byte[] data) {
        // Get the directory for the user's public pictures directory.
        String fileName = "exame.pdf";
        File pdfFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
        FileOutputStream outputStream;
        byte[] bytes;

        try{
            if(pdfFile.exists()){
                    pdfFile.delete();
                }
            pdfFile.createNewFile();

            outputStream = new FileOutputStream(pdfFile);
            outputStream.write(String.valueOf(response).getBytes());
            outputStream.close();    
        }
        catch (Exception e){
            Log.e("PDF CREATION", "FILE NOT CREATED");
            e.printStackTrace();
        }

It does create the PDF file. But it is corrupted.

Upvotes: 0

Views: 1881

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109532

String uses internally Unicode, char is two bytes UTF-16. So from bytes to String and inverse, the bytes are interpreted as being text in some charset, and a conversion takes place. This not only is slow, an uses double memory, but also causes errors.

Just use bytes:

//Response
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
byte[] buffer = new byte[1024];
int n;
while ((n = in.read(buffer)) > 0) {
    baos.write(buffer,0, n);
}
in.close();
byte[] response = baos.toByteArray();

Now you can write a file. You could immediately write to a FileOutputStream instead of to the ByteArrayOutputStream.

Upvotes: 1

Related Questions