Wednesday, August 26, 2009

PDF_read_write_diplay_operations

Invoking service to display the PDF file (the PDF file DB)
Jsp file

Table creation:
DROP TABLE IF EXISTS `thorlabswebservice`.`pdf`;
CREATE TABLE `thorlabswebservice`.`pdf` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(45) default NULL,
`file` blob,
`content_type` varchar(45) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;





Thorlab : User Login


Open PDF




Controller Class: PDFController .java
package com.optrasystems.PDF;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.optrasystems.model.User;
import com.optrasystems.mvc.validator.LoginValidator;
import com.optrasystems.mvc.validator.UserValidator;
import com.optrasystems.service.ImageProcessService;
import com.optrasystems.service.PilotSystemWebservice;
import com.optrasystems.service.UserService;
import com.optrasystems.util.PDF;

@Controller
public class PDFController {

/**
* this controller
*/
@RequestMapping("/PDF")
public String PDFOpen(HttpServletRequest request,HttpServletResponse response) {

//PDF pdf=userService.getPDF();
//request.getSession().setAttribute("pdf",pdf);
InputStream inputStream =null;
try
{
response.setContentType("application/pdf");

byte byteArray[] = new byte[5000];
PDF pdf=getPDF();
inputStream =pdf.getInputStream();

//following method open dialog box for "open", "save", nad "cancel"
//response.setHeader("Content-disposition", "attachment; filename="+pdf.getFileName()+".pdf");

//following method open the file directly....this method open the file in current page so need to open in pop-up
response.setHeader("Content-disposition", "inline; filename="+pdf.getFileName()+".pdf");

ServletOutputStream outStream = response.getOutputStream();

int n = 0;
while ( ( n = inputStream.read(byteArray)) != -1)
{
outStream.write(byteArray, 0, n);
}

outStream.flush();

inputStream.close();
outStream.close();
}
catch (Exception e)
{
e.printStackTrace();
}finally{
try{inputStream.close();

}catch (Exception e) {
e.printStackTrace();
}
}
//return "viewPDF";
return null;
}

//reading Pdf from DB.
public PDF getPDF(){

try{
// PDF class is DTO class
PDF result = (PDF) this.getHibernateTemplate().execute(
(new HibernateCallback() {

public PDF doInHibernate(Session session)
throws HibernateException, SQLException {
//reading Pdf from DB.
String squery = " SELECT name,file FROM PDF WHERE id = 3";
Statement statement = session.connection().createStatement();
ResultSet resultSet = statement.executeQuery(squery.toString());
resultSet.next();
PDF pdf=new PDF();
pdf.setFileName(resultSet.getString(1));
pdf.setInputStream(resultSet.getBinaryStream(2));
return pdf;
}

}));
return result;

}catch (Exception e) {
logger.error(""+ e.getMessage());
}
return null;
}
}

'PDF' DTO class: PDF.java
package com.optrasystems.util;
import java.io.InputStream;

/**
* @author k.panchani
*
*/
public class PDF {

private String fileName;
private InputStream inputStream;


public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
}
==========================================================================
General Reading and writing PDF file with DB

/**
*
*/
package com.optrasystems.PDF;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

/**
* @author k.panchani
* this class having oprations related to PDF file
*
*/
public class TestConnection {

/**
* @param args
*/
public static void main(String[] args) {
try{
TestWritePDF();
//TestReadPDF();
//Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + "c:\\chart.pdf");
}catch (Exception e) {
e.printStackTrace();
}

}
/** this method takes pdf file from C:\\Visio-PilotSystemSequence.pdf and
* inserting Pdf file into DB
*/
public static void TestWritePDF()throws Exception{
Connection c=null;
try{
c=getConnection();
String sql = "INSERT INTO PDF VALUES (?, ?, ?,?)";
PreparedStatement stmt = c.prepareStatement(sql);
stmt.setInt(1, 3);
stmt.setString(2, "Visioccccccc");

File image = new File("C:\\Visio-PilotSystemSequence.pdf");
FileInputStream fis = new FileInputStream(image);
stmt.setBinaryStream(3, fis, (int) image.length());
//stmt.setInt(4,image.)
stmt.execute();
c.close();

}catch (Exception e) {
e.printStackTrace();
}finally{
if(c!=null){
c.close();
}
}
}
//reading PDF file from DB and Storing in "E" drive
public static void TestReadPDF()throws Exception{
Connection c=null;
try {
c=getConnection();
String sql = "SELECT name,file FROM PDF WHERE id = 2 ";
PreparedStatement stmt = c.prepareStatement(sql);
ResultSet resultSet = stmt.executeQuery();
while (resultSet.next()) {
String name = resultSet.getString(1);
File image = new File("E:\\"+name+".pdf");
FileOutputStream fos = new FileOutputStream(image);

byte[] buffer = new byte[1];
InputStream is = resultSet.getBinaryStream(2);
while (is.read(buffer) > 0) {
fos.write(buffer);
}
}
}catch (Exception e) {
e.printStackTrace();
}finally{
if(c!=null){
c.close();
}
}
}

//this method get the Pdf file as bytes and return to caller
public static byte[] getBLOB() throws Exception {
Connection conn=null;
ResultSet rs = null;
PreparedStatement pstmt = null;
String query = "SELECT file FROM PDF WHERE id = ?";
try {
conn=getConnection();
pstmt = conn.prepareStatement(query);
pstmt.setInt(1, 2);
rs = pstmt.executeQuery();
rs.next();
Blob blob = rs.getBlob("file");
// materialize BLOB onto client
return blob.getBytes(1, (int) blob.length());
} finally {
rs.close();
pstmt.close();
conn.close();
}
}
public Connection getConnection(){
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
return DriverManager.getConnection("jdbc:mysql://localhost:3306/thorlabs","root","");
//return DriverManager.getConnection("jdbc:mysql://192.168.100.137:3306/formsjsf","root","pass");

}
catch(Exception e){
System.out.println("error:ConnectionMaker::getConnection()");
e.printStackTrace();
return null;
}
}

}

No comments: