如何在JSP中打开PDF文件

时间:2014-05-13 05:33:57

标签: java jsp pdf jasper-reports

我有一个Web应用程序,我使用 JasperReport 创建PDF报告。我托管了我的网站。

<%@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>

我接受用户的发票号码并打开该发票的PDF文件。

我的问题是我的pdf文件正在创建并存储到路径中,但是,我不知道如何打开它。 Windows中有一个方法RunTime.getRunTime.exec()。但我认为这不起作用,因为我已经将我的Web应用程序托管到免费域,这种方法在那里不起作用。  请告诉我上述方法的替代方法,以便我可以打开存储在特定路径中的PDF文件。

6 个答案:

答案 0 :(得分:2)

只需使用response.sendRedirect()。

答案 1 :(得分:1)

<%@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>

答案 2 :(得分:0)

你可以使用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());
   }
}

(如果Servlet 3.0不可用,那么以通常的方式将其映射到web.xml中,如果Java 7不可用,则以通常的方式使用读/写循环)

只需将此类完整地复制到您的项目中,然后通过/contextpath/Test.pdf而不是/contextpath/youroriginal.jsp打开所需的PDF文件(在将其组织到包中并在类中自动完成必要的导入之后) ,当然)。

E.g。如下所示,您希望以内联方式显示PDF:

<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>

答案 3 :(得分:0)

import java.io.File;
import java.io.IOException;

/** @author Taher_JAVAHUNTER*/
public class GeneratePDF {

String logUserId = "0";
public String path = "c:/PDF";

public void genrateCmd(String reqURL, String reqQuery, String folderName, String id) {
    try {
        File destFoldereGP = new File("c:/eGP");
        if (destFoldereGP.exists() == false) {
            destFoldereGP.mkdirs();
        }

        File destFolderPDF = new File("c:/PDF/");
        if (destFolderPDF.exists() == false) {
            destFolderPDF.mkdirs();
        }

        File destFolder = new File("c:/PDF/" + folderName);
        if (destFolder.exists() == false) {
            destFolder.mkdirs();
        }

        File destFolder2 = new File("c:/PDF/" + folderName + "/" + id);
        if (destFolder2.exists() == false) {
            destFolder2.mkdirs();
        }
    } catch (IOException e1) {
        System.out.println("Exception::" + e1);
    } catch (Exception e) {
        System.out.println("Exception::" + e);
    }
}
}

答案 4 :(得分:0)

如果您想在网页中显示jasper报告输出,最简洁的解决方案是将报告输出为HTML,并将输出直接发送到浏览器。

通过一些额外的工作,您可以创建一个界面,允许用户更改UI中的排序顺序和列宽,并将这些更改传递给报表对象以便重新呈现。

第二个最佳选择是在您的网页中使用Jasper Report Viewer作为applet,这样您就可以使用本机jasper报告格式查看报告。

答案 5 :(得分:-1)

我建议不要在JSP中生成PDF。

而是生成PDF VIA Action并通过servlet提供内容。

http://www.avajava.com/tutorials/lessons/how-do-i-serve-up-a-pdf-from-a-servlet.html?page=1

Display Pdf in browser using java servlet

你有可能因为你有权访问HTTP响应,但这是丑陋和可耻的

<%@ page import="org.apache.commons.io.FileUtils" %>
<%
byte[] pdfByteArray = FileUtils.readFileToByteArray(pdfFile);
response.setContentType("application/pdf");
response.getOutputStream().write(pdfByteArray);
response.getOutputStream().flush();
%>

来自 Displaying pdf in jsp