如何使用 odoo 网站页面上的按钮下载报告文件?

How can I download report file from using a button on odoo website page?

我需要使用 odoo 网站页面 上的按钮下载 odoo 报告。 我所做的是:

<a class="btn btn-primary hidden-print cms-print-pdf" t-att-href="'/cms/report/print?id='+str(main_object.id)">
                            <span><i class="fa fa-print" aria-hidden="true"></i>
                            <!--<input type="hidden" id="cms_page_id" t-att-value="main_object.id"/>-->
                            </span>
                            Print</a>

在我的控制器中

@http.route(['/cms/report/print'], type='http', auth="public", website=True)
def print_saleorder(self, **kw):
    cr, uid, context = request.cr, SUPERUSER_ID, request.context
    sale_order_id = request.session.get('sale_last_order_id')
    if 2:
        pdf = request.registry['report'].get_pdf(cr, uid, [2], 'x.cms_html_body', data=None,
                                                 context=context)
        pdfhttpheaders = [('Content-Type', 'application/pdf'), ('Content-Length', len(pdf))]

        return request.make_response(pdf, headers=pdfhttpheaders)

可惜我只得到了一个网页预览的输出,但是我需要直接做一个下载响应。我需要做什么?

您需要在回复中添加一个Content-Disposition header,表明这是一个附件,意味着它应该保存在本地而不是内联显示[source],例如:

@http.route(['/cms/report/print'], type='http', auth="public", website=True)
def print_saleorder(self, **kw):
    cr, uid, context = request.cr, SUPERUSER_ID, request.context
    sale_order_id = request.session.get('sale_last_order_id')
    if 2:
        pdf = request.registry['report'].get_pdf(cr, uid, [2], 'x.cms_html_body', data=None,
                                                context=context)
        pdfhttpheaders = [
            ('Content-Type', 'application/pdf'),
            ('Content-Length', len(pdf)),
            ('Content-Disposition', 'attachment; filename="report.pdf"'),
        ]
        return request.make_response(pdf, headers=pdfhttpheaders)

其中 report.pdf 将是下载文件的名称。

对您的代码的一些评论:

  • 在您的代码中,if 2: 条件没有意义,因为它的计算结果总是 True
  • 我认为您不需要显式设置集 Content-Length header,werkzeug 默认会这样做 [source]