Skip to Content
Odoo Меню
  • Увійти
  • Спробуйте це безкоштовно
  • Додатки
    Фінанси
    • Бухоблік
    • Виставлення рахунку
    • Витрати
    • Електронні таблиці (BI)
    • Документи
    • Підпис
    Продажі
    • CRM
    • Продажі
    • POS Магазин
    • POS Ресторан
    • Підписки
    • Оренда
    Веб-сайти
    • Конструктор веб-сайту
    • Електронна комерція
    • Блог
    • Форум
    • Живий чат
    • Електронне навчання
    Ланцюг поставок
    • Склад
    • Виробництво
    • PLM
    • Купівлі
    • Технічне обслуговування
    • Якість
    Кадри
    • Співробітники
    • Рекрутинг
    • Відпустки
    • Оцінювання
    • Рекомендації
    • Автотранспорт
    Маркетинг
    • Маркетинг соцмереж
    • Email-маркетинг
    • SMS-маркетинг
    • Події
    • Автом. маркетингу
    • Опитування
    Послуги
    • Проект
    • Табелі
    • Виїзне обслуговування
    • Служба підтримки
    • Планування
    • Призначення
    Продуктивність
    • Обговорення
    • Схвалення
    • IoT
    • IP-телефонія
    • База знань
    • WhatsApp
    Сторонні модулі Odoo Studio Платформа Odoo Cloud
  • Сфери
    Роздрібна торгівля
    • Книжковий магазин
    • Магазин одягу
    • Магазин меблів
    • Продуктовий магазин
    • Магазин будівельних матеріалів
    • Магазин іграшок
    Food & Hospitality
    • Бар та паб
    • Ресторан
    • Фастфуд
    • Guest House
    • Дистриб'ютор напоїв
    • Hotel
    Real Estate
    • Real Estate Agency
    • Архітектурна фірма
    • Будівництво
    • Управління нерухомістю
    • Садівництво
    • Асоціація власників нерухомості
    Consulting
    • Accounting Firm
    • Партнер Odoo
    • Marketing Agency
    • Юридична фірма
    • Придбання Талантів
    • Аудит та сертифікація
    Виробництво
    • Textile
    • Metal
    • Furnitures
    • Food
    • Brewery
    • Корпоративні подарунки
    Здоров'я & Фітнес
    • Спортивний клуб
    • Оптика
    • Фітнес-центр
    • Практики здоров'я
    • Аптека
    • Салон краси
    Trades
    • Ремонтник
    • IT-обладнання та Підтримка
    • Solar Energy Systems
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Others
    • Nonprofit Organization
    • Екологічна агенція
    • Оренда білбордів
    • Фотографія
    • Лізинг велосипедів
    • Реселлер програмного забезпечення
    Browse all Industries
  • Спільнота
    Навчання
    • Навчальний посібник
    • Документація
    • Сертифікації
    • Тренування
    • Блог
    • Подкаст
    Сприяйте Освіті
    • Програма навчання
    • Бізнес гра Scale Up!
    • Відвідайте Odoo
    Отримайте програмне забезпечення
    • Завантаження
    • Порівняйте версії
    • Релізи
    Співпрацюйте
    • Github
    • Форум
    • Події
    • Переклади
    • Стати партнером
    • Services for Partners
    • Зареєструйте вашу бухгалтерську фірму
    Отримайте послуги
    • Знайдіть партнера
    • Знайдіть бухгалтера
    • Зустріньтеся з консультантом
    • Послуги з впровадження
    • Референси клієнтів
    • Підтримка
    • Оновлення
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Отримати демо
  • Ціни
  • Допомога

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Бухоблік
  • Склад
  • PoS
  • Проект
  • MRP
All apps
Вам необхідно зареєструватися, щоб взаємодіяти зі спільнотою.
All Posts Люди Значки
Мітки (View all)
odoo accounting v14 pos v15
Про цей форум
Вам необхідно зареєструватися, щоб взаємодіяти зі спільнотою.
All Posts Люди Значки
Мітки (View all)
odoo accounting v14 pos v15
Про цей форум
Допомога

Invoice number into the pdf file name

Підписатися

Отримуйте сповіщення про активність щодо цієї публікації

Це запитання позначене
pdfinvoicefilename
27 Відповіді
41654 Переглядів
Аватар
Christian Douville

On Print Invoice action, the .pdf file name is not, by default, completed with the invoice number. Is there any variable i can put into the Report name header that would retrieve the Invoice number ?

24
Аватар
Відмінити
Christian Douville
Автор

Thanks. The pdf content does report the invoice number. My aim is to have the file name with the invoice number. Something like "Invoice IN-FR-1303-0008.pdf"

Ahmet Altinisik

I also need this so tired of renaming filenames for every report.

Christian Douville
Автор

Additional information, the xml for creating the report contains attachment="(object.state in ('open','paid')) and ('INVOICE_'+(object.number or '').replace('/','')+'.pdf')", so the assumption is that the number should be available into the file name

Christian Douville
Автор

Implementing/activating the Knowledge module provides the solution, as the pdf document is attached to the Account with the accurate file name (ie INVOICE + invoice number+.pdf)

Ahmet Altinisik

@Christian You have to download again the file so it is a workaround but not the solution you have to download it again after downloading the file.

Michael Karrer

The same problem for me!

I really want to have the same functionality as for "save as attachment" for all of the print buttons! Drives me nuts to always download the document twice just for the right file name...

Any idea?!?

Аватар
AJ Schrafel Paper Corp
Найкраща відповідь

You must edit the account/report/account_print_invoice.rml filename dynamically.

<document filename="Invoices.pdf">

is one of the first lines. I am not exactly sure how to do this, but I would love to know the answer.

2
Аватар
Відмінити
Christian Douville
Автор

Not sure i have to do it, as the Settings-Technical/Actions/Reports and Settings-Technical/Actions/Action Bindings look like doing this (with the optional parameters)

AJ Schrafel Paper Corp

Yes, i agree, but that action is not applied to files created when you hit the print button, just the file that is attached to the invoice after you hit the print button. There must be a way to apply that same action to the file that is automatically downloaded when you hit print.

Аватар
Nikunj Nakum
Найкраща відповідь

yes you can give 'name': 'Invoice ' + 'today date' in return from wizard to print report.

for example: this is function is call from print button in wizard.

def print_report(self,cr, uid, ids, context=None):
        if context is None:
           context = {}
        data = self.read(cr, uid, ids)[0]
        self_browse = self.browse(cr, uid, ids)
        
        datas = {
            'ids': [data.get('id')],
            'model': 'sale.order',
            'form': data
            }
        return {
            'type': 'ir.actions.report.xml',
            'report_name': 'custom.invvoice.report',
            'datas': datas,
            'name': 'Invoice ' + self_browse[0].start_date + ' To ' + self_browse[0].end_date  
            }

 

 

 

4
Аватар
Відмінити
Ankit H Gandhi(AHG)

Thanks @ Nikunj Nakum Your code is working

Аватар
Lara Freeke
Найкраща відповідь

I think you can use this module

https://github.com/OCA/reporting-engine/tree/8.0/report_custom_filename

Kind regard, 


3
Аватар
Відмінити
Sakli

Thanks @Lara

Аватар
Jérôme Thériault
Найкраща відповідь

For Odoo 9+:

Go to configuration, reports, look for the report you want, then use the Printed Report Filename field which can contain python expressions. Two variables can be used inside: object which is the object being printed, and time which is python time module. So you can input "object.name" without the quotes.

No need for extra module or code.

More here: http://gitlab.opengest.solutions/opengest/odoo/commit/da3d2fb1dc76654e630fba27ca3dcf03002d9431

Look for print_report_name

2
Аватар
Відмінити
Аватар
J4nus
Найкраща відповідь

I have also the same problem..

0
Аватар
Відмінити
Gunther Kohn

The problem seems to be unsolved. Is there possibly an easy solution? When I send the invoice or sale order via email, everything is well. The file name have the number included. But when I only print the invoice, I have no number in the file name. Thanks for any help

Аватар
Pascal Tremblay
Найкраща відповідь

Here is our solution to customize the sale order report PDF name with the « print » buttons.

https://www.odoo.com/forum/help-1/question/change-printed-file-name-in-webkit-report-in-odoo-59901

0
Аватар
Відмінити
Аватар
Pravitha
Найкраща відповідь

Hello,

I too faced the same problem of printing invoice pdf with Invoice number.pdf as its name.

I modified @Nikunj Nakum  answer and I got the result. Below given is the code

  #=================================================
  # Class             :    account_invoice (inherited)
  # Method          :    custom_invoice_print button
  # Description   :    This function prints the invoice and mark it as sent, so that
  #                            we can see more easily the next step of the workflow. 

  #                            Prints Invoice with invoice number as its name
  #================================================

  def custom_invoice_print(self, cr, uid, ids, context=None):
        self.write(cr, uid, ids, {'sent': True}, context=context)
        data = self.read(cr, uid, ids)[0]
        self_browse = self.browse(cr, uid, ids)
        datas = {
             'ids': ids,
             'model': 'account.invoice',
             'form': self.read(cr, uid, ids[0], context=context)
        }
        return {
            'type': 'ir.actions.report.xml',
            'report_name': 'account.invoice2',
            'datas': datas,
            'name': 'Invoice ' + self_browse[0].number  ,
            'nodestroy' : True
        }

Result:  Invoice INV14-09_018.pdf

0
Аватар
Відмінити
sengottuvel

Thanks.. It's woking well..

PY

Can we use this in place of the standards print buttons ? (the one in the bar and th one in the drop down menu) If yes, how ?

Pascal Tremblay

I'm not sure of the place to put it...

Pascal Tremblay

Should it works in Odoo V8 too?

Аватар
Michael Karrer
Найкраща відповідь

The same problem for me!

I really want to have the same functionality as for "save as attachment" for all of the print buttons! Drives me nuts to always download the document twice just for the right file name...

Any idea?!?

0
Аватар
Відмінити
Prakash

Hi to all, I updated my answer to shows invoice-number-into-the-pdf-file-name

Аватар
harsh jain
Найкраща відповідь

# -*- coding: utf-8 -*-

import ast
import base64
import csv
import glob
import itertools
import logging
import operator
import datetime
import hashlib
import os
import re
import simplejson
import time
import urllib
import urllib2
import urlparse
import xmlrpclib
import zlib
from xml.etree import ElementTree
from cStringIO import StringIO

import babel.messages.pofile
import werkzeug.utils
import werkzeug.wrappers
try:
    import xlwt
except ImportError:
    xlwt = None

import openerp
import openerp.modules.registry
from openerp.tools.translate import _
from openerp.tools import config


from openerp.addons.web import http
openerpweb = http
from openerp.addons.web.controllers.main import Reports

def content_disposition(filename, req):
    filename = filename.encode('utf8')
    escaped = urllib2.quote(filename)
    browser = req.httprequest.user_agent.browser
    version = int((req.httprequest.user_agent.version or '0').split('.')[0])
    if browser == 'msie' and version < 9:
        return "attachment; filename=%s" % escaped
    elif browser == 'safari':
        return "attachment; filename=%s" % filename
    else:
        return "attachment; filename*=UTF-8''%s" % escaped

 

class change_main(Reports):

    @openerpweb.httprequest
    def index1(self, req, action, token):
        
        action = simplejson.loads(action)

        report_srv = req.session.proxy("report")
        context = dict(req.context)
        
        context.update(action["context"])

        report_data = {}
        report_ids = context["active_ids"]
        if 'report_type' in action:
            report_data['report_type'] = action['report_type']
        if 'datas' in action:
            if 'ids' in action['datas']:
                report_ids = action['datas'].pop('ids')
            report_data.update(action['datas'])

        report_id = report_srv.report(
            req.session._db, req.session._uid, req.session._password,
            action["report_name"], report_ids,
            report_data, context)

        report_struct = None
        while True:
            report_struct = report_srv.report_get(
                req.session._db, req.session._uid, req.session._password, report_id)
            if report_struct["state"]:
                break

            time.sleep(self.POLLING_DELAY)

        report = base64.b64decode(report_struct['result'])
        if report_struct.get('code') == 'zlib':
            report = zlib.decompress(report)
        report_mimetype = self.TYPES_MAPPING.get(
            report_struct['format'], 'octet-stream')
        file_name = action.get('name', 'report')
        if 'name' not in action:
            reports = req.session.model('ir.actions.report.xml')
            res_id = reports.search([('report_name', '=', action['report_name']),],
                                    0, False, False, context)
            if len(res_id) > 0:
                file_name = reports.read(res_id[0], ['name'], context)['name']
            else:
                file_name = action['report_name']
        file_name = '%s.%s' % (file_name, report_struct['format'])
        
        ########################################################
        # PATCH TO PRINT PARTNER-ID AND INVOICE NO IN FILE NAME
        if context['active_model'] in ['sale.order','purchase.order','account.invoice']:
            model1 =req.session.model(context['active_model'])
            read=model1.read(context['active_id'],[],context)
            if read['name']!=False:
                file_name = read['name'] + ' ' + read['partner_id'][1]
                print file_name
                file_name = '%s.%s' % (file_name, report_struct['format'])
            # PATCH END
        #########################################################
        
        return req.make_response(report,
             headers=[
                 ('Content-Disposition', content_disposition(file_name, req)),
                 ('Content-Type', report_mimetype),
                 ('Content-Length', len(report))],
             cookies={'fileToken': token})
        
        
    Reports.index=index1

0
Аватар
Відмінити
harsh jain

DO NOT CHANGE THE BASE CODE JUST MAKE A MODULE AND INSTALL IT

Аватар
Prakash
Найкраща відповідь

In Existing Report Module after adding the below code able to generate Invoice Number in PDF File.

server\openerp\report\report_sxw.py in the create_single_pdf method.


    def create_single_pdf(self, cr, uid, ids, data, report_xml, context=None):
        if not context:
            context={}
        logo = None
        context = context.copy()
        title = report_xml.name
        rml = report_xml.report_rml_content
        model = context.get('active_model')
        record_id = context.get('active_id')    
        pool = pooler.get_pool(cr.dbname)

        invoice_obj = pool.get('account.invoice')
        type = report_xml.report_type
        if model == 'account.invoice' and record_id:
            invoice_val = invoice_obj.browse(cr, uid, record_id)     
            orderreference_type = invoice_val.reference or invoice_val.origin + report_xml.report_type
            type = orderreference_type.replace("pdf", ".pdf");        

        # if no rml file is found
        if not rml:
            return False
        rml_parser = self.parser(cr, uid, self.name2, context=context)
        objs = self.getObjects(cr, uid, ids, context)
        rml_parser.set_context(objs, data, ids, report_xml.report_type)
        processed_rml = etree.XML(rml)
        if report_xml.header:
            rml_parser._add_header(processed_rml, self.header)
        processed_rml = self.preprocess_rml(processed_rml,report_xml.report_type)
        if rml_parser.logo:
            logo = base64.decodestring(rml_parser.logo)
        create_doc = self.generators[report_xml.report_type]
        pdf = create_doc(etree.tostring(processed_rml),rml_parser.localcontext,logo,title.encode('utf8'))
        return pdf, type
        #return pdf, report_xml.report_type
      

Note: Core Report Module added extra code (Invoice Number in PDF File). But Better way to override  create_single_pdf method in a custom module.

 

0
Аватар
Відмінити
Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Реєстрація
Related Posts Відповіді Переглядів Дія
PDF Invoice line overflow
pdf invoice
Аватар
Аватар
Аватар
2
лип. 25
1527
Quote PDF Spacing & Layout
pdf invoice
Аватар
Аватар
1
серп. 25
2074
How to apply a customized invoice pdf to an email template
pdf invoice
Аватар
Аватар
1
черв. 24
3277
combine several lines into 1 row in print pdf odoo 15
pdf invoice odoo15
Аватар
0
січ. 25
1697
Odoo Invoice PDF download from External API
pdf invoice odoo17
Аватар
0
жовт. 24
2870
Спільнота
  • Навчальний посібник
  • Документація
  • Форум
Open Source
  • Завантаження
  • Github
  • Runbot
  • Переклади
Послуги
  • Хостинг Odoo.sh
  • Підтримка
  • Оновлення
  • Кастомні доробки
  • Навчання
  • Знайдіть бухгалтера
  • Знайдіть партнера
  • Стати партнером
Про нас
  • Наша компанія
  • Торгові активи
  • Зв'яжіться з нами
  • Вакансії
  • Події
  • Подкаст
  • Блог
  • Клієнти
  • Юридичні документи • Конфіденційність
  • Безпека
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo - це набір програм для роботи з відкритим кодом, які охоплюють всі ваші потреби компанії: CRM, електронна комерція, бухгалтерський облік, склад, точка продажу, управління проектами тощо.

Унікальна пропозиція Odoo - це одночасно дуже проста у використанні та повністю інтегрована.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now