Export JasperReport's report to pdf via Servle

2019-09-06 11:13发布

问题:

I have used the following code for exporting a jasper report to a pdf file using JSP.

response.setHeader("Content-Disposition", "inline; filename=\"application.pdf\"");
response.setContentType("application/pdf");

Connection con;

String host = "jdbc:mysql://localhost:3306/123";
String uname = "root";
String upass = "";
Class.forName("com.mysql.jdbc.Driver");      

con = DriverManager.getConnection(host, uname, upass);

String report="C:\\Users\\Acer\\Documents\\NetBeansProjects\\jasper\\1.jrxml";
JasperReport jr= JasperCompileManager.compileReport(report);
JasperPrint jasperPrint = JasperFillManager.fillReport(jr,  null, con);

JasperExportManager.exportReportToPdfFile(jasperPrint, "application.pdf");

When I run this JSP file in NetBeans, a message box with the following error appears in the browser:

"File does not begin with '%PDF-'. Local\EWH_)!50gc#"

This message comes from Adobe Reader.

Any help would be appreciated.

回答1:

Using exportReportToPdfFile() is totally wrong: you do not want to create a file, rather export to the response stream. So replace the last line of the snippet with:

OutputStream outStream = response.getOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, outStream);


回答2:

Seems everyting is ok ,except the last section ie, the export section.

Replace it with

//Exporting the report as a PDF
    System.out.println("Exporting pdf");
    JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());

    JasperExportManager.exportReportToPdfFile(jasperPrint, "report.pdf");