Tuesday, September 27, 2011

Convert Byte Array to PDF in java



import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class TestPDF {

public static void main(String[] args) throws FileNotFoundException {
Test obj = new Test();
boolean result = obj.savePDF();
System.out.println("Result of Saving PDF : "+result);
obj.getPDF();
}
public boolean savePDF() throws FileNotFoundException{
File file = new File("c:/Java/Input_File.pdf");
FileInputStream fis = new FileInputStream(file);
Connection con = null;
try{
con = DAO.getConnection();
PreparedStatement pstmt = con.prepareStatement("Insert into test (pdf) values (?)");
pstmt.setBinaryStream(1, (InputStream)fis, (int)file.length());
int flag = pstmt.executeUpdate();
con.close();
if(flag>0)
return true;
else
return false;
}catch(Exception e){
System.out.println("Exception in saving PDF : "+e);
}
return false;
}
public void getPDF(){
Connection con = null;
InputStream fetchStream = null;
try{
con = DAO.getConnection();  //Getting the Database Connection
PreparedStatement pstmt = con.prepareStatement("select pdf from test where sl=1");
ResultSet rs = pstmt.executeQuery();
if(rs.next())
{
fetchStream = rs.getBinaryStream("pdf");
}
}catch(Exception e){
System.out.println("Exception in getting PDF : "+e);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fetchStream.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
System.out.println("read " + readNum + " bytes,");
}
System.out.println("Byte array is="+bos);
} catch (Exception ex) {
ex.printStackTrace();
}
byte[] bytes = bos.toByteArray();
File someFile = new File("c:/Java/Output_File.pdf");
try{
FileOutputStream fos = new FileOutputStream(someFile);
fos.write(bytes);
fos.flush();
fos.close();
}catch(Exception e){
}
}
}

4 comments:

  1. Check out the following post, you can find some very useful information related to Writing byte array to pdf file in java.

    http://www.aspose.com/community/forums/thread/505213/write-byte-array-into-pdf-file-by-java-program.aspx

    ReplyDelete
    Replies
    1. My Java Works: Convert Byte Array To Pdf In Java >>>>> Download Now

      >>>>> Download Full

      My Java Works: Convert Byte Array To Pdf In Java >>>>> Download LINK

      >>>>> Download Now

      My Java Works: Convert Byte Array To Pdf In Java >>>>> Download Full

      >>>>> Download LINK lr

      Delete
  2. My Java Works: Convert Byte Array To Pdf In Java >>>>> Download Now

    >>>>> Download Full

    My Java Works: Convert Byte Array To Pdf In Java >>>>> Download LINK

    >>>>> Download Now

    My Java Works: Convert Byte Array To Pdf In Java >>>>> Download Full

    >>>>> Download LINK LF

    ReplyDelete