Symfony2 FOSRESTBundle REST API to return PDF

走远了吗. 提交于 2019-11-30 15:41:16

So I've found the solution (I will describe how to enable 2 output formats: PDF and XLS):

1) This section in config.yml is not needed:

framework:
    [...some old stuff here...]
    request:
        formats:
            pdf: 'application/pdf'

2) fos_rest.format_listener section in config.yml should look like this:

format_listener:
    rules:
        -
            path:                 '^/api/my/bacon.*\.xls$'
            host:                 ~
            prefer_extension:     false
            fallback_format:      json
            priorities:           [xls, json]
        -
            path:                 '^/api/my/bacon.*\.pdf$'
            host:                 ~
            prefer_extension:     false
            fallback_format:      json
            priorities:           [pdf, json]
        -
            path:                 ~
            host:                 ~
            prefer_extension:     true
            fallback_format:      html
            priorities:           [html,json]

3) need to add service section into fos_rest in config.yml

fos_rest:
[...]
    service:
        view_handler: my.view_handler

4) services root section in config.yml should look like

services:
    my.view_handler.xls:
        class: Lobster\MyBundle\View\XlsViewHandler
    my.view_handler.pdf:
        class: Lobster\MyBundle\View\PdfViewHandler
    my.view_handler:
        parent: fos_rest.view_handler.default
        calls:
            - ['registerHandler', ['xls', [@my.view_handler.xls, 'createResponse'] ] ]
            - ['registerHandler', ['pdf', [@my.view_handler.pdf, 'createResponse'] ] ]

And this is it. Now it works perfect

If files will have different data content, then Controller could as well generate file on their own, returning results in BinaryFileResponse.

  • No need to change any configuration
  • _format can be used to pick desired file format
  • All code reside inside controller (and some services related to particular format gen), so adding new stuff or changing existing require changes in small number of files.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!