将StringBuffer转换为PDF文件

时间:2016-09-23 23:17:14

标签: java android pdf

我正在这个项目中工作,我从以下形式的网络服务中收到:

%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�����.......

我不能将其视为PDF格式。 我试图将这些字节插入到pdf文件中,但它不起作用。 我也尝试使用webview打开...没有成功。

这里有一些代码:

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();
        }

确实会创建PDF文件。但它已被破坏。

1 个答案:

答案 0 :(得分:0)

String使用内部Unicode,char是两个字节UTF-16。因此,从字节到字符串和反向,字节被解释为某些字符集中的文本,并且发生转换。这不仅很慢,而且使用双内存,但也会导致错误。

只需使用字节:

//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();

现在你可以写一个文件了。您可以立即写入FileOutputStream而不是ByteArrayOutputStream。