You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Odoo 16:如何通过Python代码无模板生成自定义PDF报告

在Odoo 16中纯Python代码生成PDF报告(无需模板)

要实现点击向导按钮直接生成PDF,核心是利用Odoo内置工具将HTML内容转换为PDF,再返回下载响应。以下是具体实现步骤:

1. 向导模型中添加按钮处理方法

在自定义向导模型里,新增按钮触发的方法,完成HTML转PDF并返回下载响应:

from odoo import models, fields, api
from odoo.tools.misc import html2pdf
from odoo.http import request

class CustomReportWizard(models.TransientModel):
    _name = 'custom.report.wizard'
    _description = 'Custom Report Wizard'

    file_name = fields.Char(string='File Name', required=True)
    model_id = fields.Many2one('ir.model', string='Model', required=True)
    content_report = fields.Html(string='Report Content', required=True)

    @api.multi
    def action_generate_pdf(self):
        self.ensure_one()
        # 处理文件名,确保后缀为pdf
        file_name = self.file_name if self.file_name.endswith('.pdf') else f"{self.file_name}.pdf"
        # 将HTML内容转换为PDF字节流
        pdf_data = html2pdf(self.content_report)
        # 构造下载响应
        return request.make_response(
            pdf_data,
            headers=[
                ('Content-Type', 'application/pdf'),
                ('Content-Disposition', f'attachment; filename="{file_name}"'),
            ]
        )

2. 配置向导视图中的按钮

在向导的表单视图里添加触发按钮,注意按钮类型设为object:

<odoo>
    <record id="custom_report_wizard_form" model="ir.ui.view">
        <field name="name">custom.report.wizard.form</field>
        <field name="model">custom.report.wizard</field>
        <field name="arch" type="xml">
            <form>
                <header>
                    <button name="action_generate_pdf" string="生成PDF" type="object" class="btn-primary"/>
                    <button string="取消" special="cancel" class="btn-secondary"/>
                </header>
                <sheet>
                    <group>
                        <field name="file_name"/>
                        <field name="model_id"/>
                        <field name="content_report" colspan="4" height="400"/>
                    </group>
                </sheet>
            </form>
        </field>
    </record>
</odoo>

3. 关键注意事项

  • HTML完整性:content_report的HTML内容最好包含完整的<html>、<head>、<body>标签,内嵌<style>定义样式,避免PDF排版混乱。示例:
    <html>
        <head>
            <meta charset="UTF-8">
            <style>
                body { font-family: Arial, sans-serif; }
                h1 { color: #2c3e50; }
                .page-break { page-break-after: always; }
            </style>
        </head>
        <body>
            <h1>自定义报告</h1>
            <p>报告内容...</p>
            <div class="page-break"></div>
            <p>第二页内容...</p>
        </body>
    </html>
    
  • 依赖检查:确保Odoo服务器已安装符合版本要求的wkhtmltopdf(Odoo 16推荐0.12.5及以上版本),否则HTML转PDF会失败。
  • 资源访问:如果HTML引用外部图片或样式,需确保服务器能访问到资源,或者将资源转为base64内嵌到HTML中。

内容的提问来源于stack exchange,提问作者Ing

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 19:13:41