java 使用 Spring MVC 返回一个 PDF 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27406178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:46:12  来源:igfitidea点击:

Return a PDF file with Spring MVC

javaspringspring-mvcpdf

提问by Fernando Pineda

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.

实际上,我有这个功能,我得到了一个框架,我在其中设置了 URL ( ip:port/birt/preview?__report=report.rptdesign&__format=pdf&parameters...) 并且该框架呈现了 PDF 文件。

But I want that URL hidden...

但我想隐藏那个网址...

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

我需要使用 Spring MVC 返回一个 PDF 文件,但该 PDF 是由另一个应用程序生成的。

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?

这意味着我有另一个应用程序(Eclipse Birt Engine),我通过 URL ( ip:port/birt/preview?__report=report.rptdesign&__format=pdf&parameters...)传递参数并生成一个 PDF 文件,我需要从我的控制器获取该 PDF 并使用 Spring MVC 返回它。有人可以帮忙吗?

回答by Alan Hay

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

回答by cjstehno

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

PDF 内容只是字节,因此您可以将 PDF 内容字节写入 HttpResponse 输出流。