コンテンツへスキップ
メニュー
この質問にフラグが付けられました
4 返信
10413 ビュー

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?

著作者

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

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

最善の回答

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

Thanks, it works fine!

著作者 最善の回答

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 :)

アバター
破棄
最善の回答

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.

最善の回答

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?

関連投稿 返信 ビュー 活動
1
3月 15
5646
2
3月 15
6514
0
3月 15
3336
4
12月 23
11251
1
3月 18
3928