Java: Need to create PDF from byte-Array

Viewed 113614

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?

4 Answers

Read from file or string to bytearray.

byte[] filedata = null;
String content = new String(bytearray);
content = content.replace("\r", "").replace("\uf8ff", "").replace("'", "").replace("\"", "").replace("`", "");
String[] arrOfStr = content.split("\n");
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
try (PDPageContentStream cs = new PDPageContentStream(document, page)) {
    // setting font family and font size
    cs.beginText(); 
    cs.setFont(PDType1Font.HELVETICA, 14);
    cs.setNonStrokingColor(Color.BLACK);
    cs.newLineAtOffset(20, 750);
    for (String str: arrOfStr) {
        cs.newLineAtOffset(0, -15);
        cs.showText(str);
    }
    cs.newLine();
    cs.endText();
}
document.save(znaFile);
document.close();
 public static String getPDF() throws IOException {

        File file = new File("give complete path of file which must be read");
        FileInputStream stream = new FileInputStream(file);
        byte[] buffer = new byte[8192];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int bytesRead;enter code here
        while ((bytesRead = stream.read(buffer)) != -1) {
            baos.write(buffer, 0, bytesRead);
        }
        System.out.println("it came back"+baos);
        byte[] buffer1= baos.toByteArray();
        String fileName = "give your filename with location";

        //stream.close();
        
        
         FileOutputStream outputStream =
                    new FileOutputStream(fileName);
         
         outputStream.write(buffer1);
        
         return fileName;
        
    }
Related