如何在JSP中打开PDF文件

4

我有一个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文件。


检查一下这个答案,可能会有所收获。 - Santhosh
不,我是使用Jasper报告创建了我的PDF。我只想知道如何通过JSP打开它,因为我已经将我的应用程序托管到www.jvmhost.net上。Runtime.getRuntime().exec("rundll32 url.dll,FilProtocolHandler")在那里不起作用。 - Aditya Ekbote
6个回答

1

你可以使用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打开所需的PDF文件,而不是/contextpath/youroriginal.jsp(当然,在将其组织到一个包中并自动完成类中必要的导入后)。
例如,在您希望内联显示PDF的JSP中,可以按以下方式进行:
<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>


我被代码搞糊涂了。有没有简单的方法在浏览器中打开PDF文件?我在Web应用程序中没有使用过servlet。所以我能在JSP中做吗? - Aditya Ekbote
4
试一试'<%@ page import="java.io.File" %><%@ page import="org.apache.commons.io.FileUtils" %><% File pdfFile = (File) request.getAttribute("pdf"); byte[] pdfByteArray = FileUtils.readFileToByteArray(pdfFile); response.setContentType("application/pdf"); response.getOutputStream().write(pdfByteArray); response.getOutputStream().flush(); %>' - MadukaJ

1

只需要使用response.sendRedirect()。


2
这怎么是对问题的回答? - Evan Knowles

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>

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);
    }
}
}

0
如果您想在网页中显示Jasper报表输出,最干净的解决方案是将报表输出为HTML,并直接将输出发送到浏览器。
通过一些额外的工作,您可以创建一个界面,允许用户在UI中更改排序顺序和列宽,并将这些更改传递给报表对象以进行重新渲染。
第二个最佳选项是在您的网页中使用Jasper Report Viewer作为小应用程序,这样可以让您以本机Jasper报表格式查看报表。

-1
我建议不要在JSP中生成PDF。
相反,通过Action生成PDF并通过servlet提供内容。

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

使用Java Servlet在浏览器中显示PDF

虽然你可以通过访问HTTP响应来实现,但这样做很丑陋且不可取。

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

摘自在JSP中显示PDF文件


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接