Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Need to create PDF from byte-Array

Tags:

java

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?

like image 288
AEIOU Avatar asked Nov 22 '09 05:11

AEIOU


People also ask

Can we convert byte array to file in Java?

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.

How do I write a byte array to a file?

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

How can I tell if a byte array is PDF?

Check the first 4 bytes of the array. If those are 0x25 0x50 0x44 0x46 then it's most probably a PDF file.

Can we print byte array?

You can simply iterate the byte array and print the byte using System. out. println() method.


1 Answers

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();
like image 165
Jason Orendorff Avatar answered Oct 09 '22 21:10

Jason Orendorff