java - Creating corrupted PDF from bytearray -
i trying generate pdf byte array in java returned through webservice, pdf cannot opened. shows corrupted, have attached code. pls got wrong?
jsonobject o = new jsonobject(outjson); jsonobject jsonob = o.optjsonobject("pdf details"); byte[] pdfbyte=jsonob.optstring("pdf bytearray").tostring().getbytes(); string str1 = new string(pdfbyte); file somefile = new file("c:/users/acer/desktop/test1.pdf"); fileoutputstream fos = new fileoutputstream(somefile); byte[] bytedata = str1.getbytes(); byte[] bytedata1 = test.getbytes(); fos.write(pdfbyte); fos.flush(); fos.close();
following json webservice:
{"pdf details": { "id":"121", "pdf bytearray":"[b@62a58cd" } }
following webservice code outputs bytearray in json:
public response getpdf( ) { string flag=null; file file = new file("c:/users/acer/desktop/report.pdf"); fileinputstream fileinputstream; byte[] data = null; byte[] finaldata = null; bytearrayoutputstream bytearrayoutputstream = null; fileinputstream = new fileinputstream(file); data = new byte[(int)file.length()]; finaldata = new byte[(int)file.length()]; bytearrayoutputstream = new bytearrayoutputstream(); fileinputstream.read(data); bytearrayoutputstream.write(data); finaldata = bytearrayoutputstream.tobytearray(); fileinputstream.close(); system.out.println(finaldata); jsonobject jsonobject = new jsonobject(); jsonobject mainjsonobject = new jsonobject(); jsonobject.put("id","121"); jsonobject.put("pdf bytearray",finaldata); mainjsonobject.put("pdf details",jsonobject); flag = "" + mainjsonobject; return response.status(200).entity(flag).build(); }
i got right following chnge in webservice:
public response getpdf( ) { string flag=null; file file = new file("c:/users/acer/desktop/report.pdf"); fileinputstream fileinputstreamreader = new fileinputstream(file); byte[] bytes = new byte[(int)file.length()]; fileinputstreamreader.read(bytes); string encodedbase64 = new string(base64.encodebase64(bytes)); jsonobject jsonobject = new jsonobject(); jsonobject mainjsonobject = new jsonobject(); jsonobject.put("id","121"); jsonobject.put("pdf bytearray",encodedbase64); mainjsonobject.put("pdf details",jsonobject); flag = "" + mainjsonobject; return response.status(200).entity(flag).build(); }
my client:
string encodedbase64=jsonob.optstring("pdf bytearray"); byte[] decodedbytes = base64.decodebase64(encodedbase64); system.out.println("decbyte "+decodedbytes); file somefile = new file("c:/users/acer/desktop/test.pdf"); outputstream fos = new fileoutputstream(somefile); fos.write(decodedbytes); fos.flush(); fos.close();
Comments
Post a Comment