From a DB2 table I've got blob which I'm converting to a byte array so I can work with it. I need to take the byte array and create a PDF out of it.
This is what I have:
static void byteArrayToFile(byte[] bArray) {  
    try {  
        // Create file  
        FileWriter fstream = new FileWriter("out.pdf");  
        BufferedWriter out = new BufferedWriter(fstream);  
        for (Byte b: bArray) {  
            out.write(b);  
        }  
        out.close();  
    } catch (Exception e) {  
        System.err.println("Error: " + e.getMessage());  
    }  
}
But the PDF it creates is not right, it has a bunch of black lines running from top to bottom on it.
I was actually able to create the correct PDF by writing a web application using essentially the same process. The primary difference between the web application and the code about was this line:
response.setContentType("application/pdf");
So I know the byte array is a PDF and it can be done, but my code in byteArrayToFile won't create a clean PDF.
Any ideas on how I can make it work?
In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file. Example: Java.
Java – How to save byte[] to a file write is the simplest solution to save byte[] to a file. // bytes = byte[] Path path = Paths. get("/path/file"); Files. write(path, bytes);
Check the first 4 bytes of the array. If those are 0x25 0x50 0x44 0x46 then it's most probably a PDF file.
You can simply iterate the byte array and print the byte using System. out. println() method.
Sending your output through a FileWriter is corrupting it because the data is bytes, and FileWriters are for writing characters. All you need is:
OutputStream out = new FileOutputStream("out.pdf");
out.write(bArray);
out.close();
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With