Fernando Pineda
Fernando Pineda

Reputation: 83

Return a PDF file with Spring MVC

Actually, I have that functionality, I got a frame where I set the URL (ip:port/birt/preview?__report=report.rptdesign&__format=pdf&parameters...) and that frame renders the PDF file.

But I want that URL hidden...

I need return a PDF file with Spring MVC but that PDF is generated by another application.

This means I got another app (Eclipse Birt Engine) that I pass the parameters through of an URL (ip:port/birt/preview?__report=report.rptdesign&__format=pdf&parameters...) and it generates a PDF file, I need from my controller get that PDF and return it with Spring MVC. Could somebody help?

Upvotes: 7

Views: 22223

Answers (2)

Alan Hay
Alan Hay

Reputation: 23226

That would be like the below:

@Controller
@RequestMapping("/generateReport.do")
public class ReportController

    @RequestMapping(method = RequestMethod.POST)
    public void generateReport(HttpServletResponse response) throws Exception {

        byte[] data = //read PDF as byte stream

        streamReport(response, data, "my_report.pdf"));
    }

    protected void streamReport(HttpServletResponse response, byte[] data, String name)
            throws IOException {

        response.setContentType("application/pdf");
        response.setHeader("Content-disposition", "attachment; filename=" + name);
        response.setContentLength(data.length);

        response.getOutputStream().write(data);
        response.getOutputStream().flush();
    }
}

Upvotes: 12

cjstehno
cjstehno

Reputation: 13984

PDF content is just bytes so you can just write the PDF content bytes to the HttpResponse output stream.

Upvotes: 0

Related Questions