How to open PDF file in JSP

17,925

Solution 1

Simply use response.sendRedirect().

Solution 2

<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Blob"%>
<%@page import="java.io.OutputStream"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>View File</title>
</head>
<body>
   <%


String connectionURL = "jdbc:mysql://localhost:3306/database_name";

String user = "username";
String pass = "password";

Connection con = null;
Statement stat= null;
ResultSet rs= null;

PreparedStatement ps=null;
String Filename = "Filename";
Blob file=null;
byte[] filedata = null;

try
{

try
{
     Class.forName("com.mysql.jdbc.Driver");
    con = DriverManager.getConnection(connectionURL, user, pass);
    stat = con.createStatement();
}
catch(Exception e) {
    out.println("Error During connection to the database : " +e.getMessage());
}
s1="select * from doc where Book_Name='"+Filename+"'";
rs=stat.executeQuery(s1);
try{
    if(rs.next ())
    {
        file=rs.getBlob("Book");
        filedata=file.getBytes(1, (int) file.length());

}


    else
    {
        out.println("file not found.");
        return;

    }
    response.setContentType("application/pdf");
    response.setHeader("content-Disposition","inline");
    response.setContentLength(filedata.length);
    OutputStream output =response.getOutputStream();
    output.write(filedata);
    output.flush();
}
catch(Exception e)
{
 out.println("Error while retriving data : " +e.getMessage());     
}

%>

 <%
  }
 catch(Exception e)
 {
 out.println("Error in application :"+e.getMessage());
 }

 %>
</body>
</html>

Solution 3

you can use servlet.

@WebServlet("/Test.pdf")
public class PdfServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    File file = new File("D:\\Test\\Test.pdf");
    response.setHeader("Content-Type",    getServletContext().getMimeType(file.getName()));
    response.setHeader("Content-Length", String.valueOf(file.length()));
    response.setHeader("Content-Disposition", "inline; filename=\"Test.pdf\"");
    Files.copy(file.toPath(), response.getOutputStream());
   }
}

(if Servlet 3.0 is not available, then map it in web.xml the usual way, if Java 7 is not available, then use a read/write loop the usual way)

Just copypaste this class in its entirety into your project and open the desired PDF file by /contextpath/Test.pdf instead of /contextpath/youroriginal.jsp (after having organized it in a package and autocompleted the necessary imports in the class, of course).

E.g. as follows in a JSP where you'd like to show the PDF inline:

<object data="${pageContext.request.contextPath}/Test.pdf" 
type="application/pdf" width="500" height="300">
<a href="${pageContext.request.contextPath}/Test.pdf">Download file.pdf</a>

Share:
17,925
Aditya Ekbote
Author by

Aditya Ekbote

Core , Advanced Java Programmer with knowledge of struts 2.0, hibernate. I am professional person willing to gain and spread knowledge. I believe why reinvent the wheel if there are much more Solutions to programming problems. So I do love Stack Overflow.

Updated on June 26, 2022

Comments

  • Aditya Ekbote
    Aditya Ekbote almost 2 years

    I have a web application in which I am creating PDF reports using JasperReport. I have hosted my website.

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <%@page import="java.sql.*" %>
    <%@page import="net.sf.jasperreports.engine.JasperExportManager"%>
    <%@page import="net.sf.jasperreports.engine.JasperExportManager"%>
    <%@page import="net.sf.jasperreports.view.JasperViewer"%>
    <%@page import="net.sf.jasperreports.engine.JasperPrint"%>
    <%@page import="net.sf.jasperreports.engine.JasperReport"%>
    <%@page import="net.sf.jasperreports.engine.JasperFillManager"%>
    <%@page import="net.sf.jasperreports.engine.JRResultSetDataSource"%>
    <%@page import="net.sf.jasperreports.engine.JasperCompileManager"%>
    <%@page import="net.sf.jasperreports.*"%>
    <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%
            String invno=request.getParameter("invno");
            try {
            String absolutePath = getServletContext().getRealPath("clDS_Close.jrxml");
            JasperReport jasperReport=JasperCompileManager.compileReport(absolutePath);
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn =   DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","aadi");
    
            Statement stmt = null;
            ResultSet rset = null;
            Statement st2=conn.createStatement();
    
            String queryString = "select tbl_invoice.*,tbl_package.package_name,tbl_package.basic_hr,tbl_package.basic_km,tbl_package.amount from tbl_invoice inner join tbl_package on tbl_invoice.package_id=tbl_package.package_id where tbl_invoice.invoice_no="+invno+"";
            stmt = conn.createStatement();
            rset = stmt.executeQuery(queryString);
            JRResultSetDataSource jasperReports = new JRResultSetDataSource(rset);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,null, jasperReports);
    
            String filename=null;
            filename="CL"+invno+".pdf";
    
            //Report saved in specified path
            JasperExportManager.exportReportToPdfFile(jasperPrint,filename);
    
            //Report open in Runtime
            String createdFile = getServletContext().getRealPath(filename);
            out.println(createdFile);
              Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " +filename);
           } catch(Exception e) {
               out.println(e);
           }
        %>
    </body>
    </html>
    

    I am accepting invoice number from user and opening PDF file for that invoice.

    My problem is my pdf file is getting created and stored to path but, I don't know how to open it. There is a method RunTime.getRunTime.exec() in windows. But I think this will not work because as I have hosted my web application to free domain, this method will not work there. Please tell me alternative for above method so that I can open my PDF file stored in specific path.