How to convert a Blob object into a PDF file in Java?

37,138

Solution 1

You can use the getBinaryStream() from the ResultSet, then you can create a file from InputStream returned by the getBinaryStream().

Your code may look something like this

Connection connection = null;
Statement statement = null;
ResultSet rs = null;
  
try {
         
        Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
        connection = DriverManager.getConnection(connectionURL, "sa", "sa");
        statement = connection.createStatement();
        rs = statement.executeQuery("SELECT fileName,blobFile FROM tblBlobFiles");
     
     
        if (rs.next()) {
  
String filename = rs.getString(1);
           Blob blob = rs.getBlob(2);
          InputStream is = blob.getBinaryStream();
              FileOutputStream fos = new FileOutputStream("C:\\DownloadedFiles"+ "\\" + filename);
 
int b = 0;
while ((b = is.read()) != -1)
{
    fos.write(b); 
}
        }
    } catch (IOException e) 
    {
    e.getMessage (); e.printStackTrace(); 
System.out.println(e); 
    } 
    catch (SQLException e) 
    {
    e.getMessage (); e.printStackTrace(); 
System.out.println(e); 
    }

If you need all the blobs, do a iteration on the resultset

Solution 2

If the Blob is the binary representation of a PDF, all you need to do is get the bytes. If you wanted to write the PDF to a file, you could do...

Blob blobPdf = ...;
File outputFile = new File("/tmp/blah/whatever.pdf");
FileOutputStream fout = new FileOutputStream(outputFile);
IOUtils.copy(blobPdf.getBinaryStream(), fout);

This should write your PDF to a file called "/tmp/blah/whatever.pdf"

Solution 3

you can use Java NIO

InputStream fileBolb = rs.getBinaryStream("columnName");
ReadableByteChannel rbc = Channels.newChannel(fileBolb );
FileOutputStream fos = new FileOutputStream(filePath + fname);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
Share:
37,138
AndreaNobili
Author by

AndreaNobili

Updated on February 12, 2020

Comments

  • AndreaNobili
    AndreaNobili about 4 years

    I have the following situation into a Java application.

    From the database a retrieve this Blob object that is the representation of a PDF file on the DB:

    Blob blobPdf = cedolinoPdf.getAllegatoBlob();
    

    Now I have to convert it into a PDF file. How can I do this task?

    Tnx