JasperReports PdfServlet to save report in PDF - how can I set the filename for the browser to prompt the user?

后端 未结 1 1775
说谎
说谎 2021-01-28 16:06

Stack: JSF + PrimeFaces on JBoss AS with JasperReports

I have been using a pattern of exporting in PD

1条回答
  •  广开言路
    2021-01-28 16:48

    As to your concrete problem with the "Save as" filename, it defaults to the last path in the request URL (which is in case of /servlets/pdf indeed just pdf), unless otherwise specified in Content-Disposition header.

    The problem is not directly caused by your JSF code (although it is at its own kind of odd, but that's a different problem/question), but more in the servlet which is been mapped on /servlets/pdf. To set the desired "Save as" filename, you need to add the following line before writing any byte to the response:

    response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
    

    You can if necessary replace attachment by inline if you want to display it by default inline.

    The Internet Explorer browser, however, ignores this value and sticks to using the last path in the request URL. So to cover that browser as well, you'd need to include the desired filename in the request URL yourself and change the servlet mapping.

    E.g.

    String filename = "report-2012-08-23c.pdf";
    externalContext.redirect("servlets/pdf/" + filename);
    

    with

    @WebServlet("/servlets/pdf/*") // instead of @WebServlet("/servlets/pdf")
    

    With this URL pattern, the filename is inside the servlet available by

    String filename = request.getPathInfo().substring(1);
    

    0 讨论(0)
提交回复
热议问题