This discussion is archived
4 Replies Latest reply: May 27, 2010 1:57 PM by 807580 RSS

can u help me in resolving error, reading bytes of pdf file from http url ?

807580 Newbie
Currently Being Moderated
Here is my code below
Problem i am facing is that am getting corrupted pdf file if the size of that file is very small.
my whold process converts the txt file into pdf file and returns the url of that existing pdf file located on the server through LAN.
when i access that url i am able to see the pdf file of my input txt file.

i have a very small txt file in which there is only few words of text. say, txt file less then 300 bytes total.
i am able to get the required converted pdf file from the server and that pdf file is perfect, nothing wrong with that.
i use the url for that pdf file to read the bytes and write using the code below
code is workign fine for every pdf i read using my given code.
if i use very small txt file to generate pdf then my code fails to write bytes properly and it gives corrupted pdf file.
try {
String fileName = "test";
response.reset();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".pdf;");

String urlString = http://[server]:[port]/test.pdf

URL fileUrl = new URL(urlString);
            PrintWriter out = response.getWriter();
            ByteArrayOutputStream tmpOut = new ByteArrayOutputStream();            
            InputStream inStream = fileUrl.openStream();
//kept the size of byte large because it doesnt know how big the pdf file will be. But i am sure it wont be bigger then 25600000 bytes.           
byte[] buf = new byte[25600000];
            int lenFile;

            while (true) {
                lenFile = inStream.read(buf);
                if (lenFile == -1) {
                    break;
                }
                
                tmpOut.write(buf, 0, lenFile);                
                
            }
                     
            out.print(new String(tmpOut.toByteArray(), "ISO-8859-1"));
            tmpOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }