Odoo Help

Welcome!

This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers.

0

customize file name for RML reports

By
ASP
on 1/21/14, 9:49 AM 4,340 views

Hello Guys,

I've designed reports for my custom modules using openoffice and RML. But while printing/generating the PDF file of the report, it's opening or saving as the report name.pdf, as listed in settings>actions>reports.

My objective is to add some id or number to the file name of the corresponding report, Ex: "My Report - 123.pdf", "My Report - 234.pdf" etc.

To achieve the above, i've tried 2 approaches as mentioned below :

  1. Edit report from front end and add python code to Add attachment box and select the Reload from Attachment checkbox.

  2. Added attributes like attachment, use_attachment, multi etc. under report tag in the module_view.xml file.

But no luck. Still the report PDF is opening/saving with the old name. Pls help me with this.

Any help would be appreciated. :)

Cheers

ASP :)

What did you enter in the "Save as Attachment Prefix" field while editing the report?

Geert Surkijn
on 1/21/14, 6:34 PM

('MyReport '+(object.inv_num and (object.type)).replace('/','')+'.pdf')

where inv_num & type are the fields present in that module.

ASP
on 1/22/14, 1:58 AM
2
harsh jain
On 9/29/14, 5:51 PM

# -*- 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

DO NOT CHANGE THE BASE CODE, JUST MAKE A MODULE AND INSTALL IT. I HAVE OVERRIDEN THE BASE METHOD

harsh jain
on 9/29/14, 5:53 PM

Thanks, it works fine!

Mohamed Essakali
on 10/1/14, 6:07 PM
0
ASP
On 4/11/14, 9:30 AM

Hi All,

As I've been able to achieve exactly what I was looking for, hence sharing the approach.

For renaming any report PDF with the record ID or any dynamically varying number, I just added some lines of code in the main.py file which is present in /addons/web/controllers/

In that main.py file, there is a index function in class Reports(openerpweb.Controller):

Inside that function, we can get the report name from action['report_name'], so i just added a condition to check my report name and fetched corresponding number/id/ any value (that i wanted to add to the report name) for that record from it's module using the ORM

Then after saving my changes to that file and restarting the server............it's done.

Cheers

ASP :)

-1
Geert Surkijn
On 1/22/14, 4:57 PM

Hello,

Like the example of the invoice save action within the standard installation: (object.state in ('open','paid')) and ('INV'+(object.number or '').replace('/','')+'.pdf')

In your example I guess it would be like this: ('MyReport - '+(object.inv_num or '')+'.pdf')

When your object contains special characters you would probably want them to be deleted within the name of the file: ('MyReport - '+(object.inv_num or '').replace('/','')+'.pdf')

So if you want to use also the type field, eg: ('MyReport'+((' - '+object.inv_num) or '').replace('/','')+((' - '+object.type) or '')+'.pdf')

The difference between the two last examples is beside the use of the field type, also the smarter way we are going to place the '-' between the values. We only use them in the file name if there is a value.

the standard installation (V7.0) seems not to work (here). I always get Invoices.pdf as file name, any hints?

M. Höppner
on 4/1/14, 11:29 AM
-1
shashank verma
On 1/22/14, 7:37 AM

Hello ASP

Suppose i have created new rml file 'custom_sale.rml 'for sale module.

go to module sale -> edit sale_report.xml <report id="report_myreport" model="sale.order" name="report.sale.list" string=" My Report - 123" rml="sale/custom_sale.rml"/>

Hi Shashank, the way you mentioned above will generate all reports with this fixed name i.e., My-Report - 123.pdf, but I want to add some id or number to that name, which will vary dynamically for each report as per the corresponding id or number of that report.

ASP
on 1/22/14, 8:37 AM

Your Answer

Please try to give a substantial answer. If you wanted to comment on the question or answer, just use the commenting tool. Please remember that you can always revise your answers - no need to answer the same question twice. Also, please don't forget to vote - it really helps to select the best questions and answers!

About This Community

This community is for professionals and enthusiasts of our products and services. Read Guidelines

Question tools

2 follower(s)

Stats

Asked: 1/21/14, 9:49 AM
Seen: 4340 times
Last updated: 3/16/15, 8:10 AM