def testRequiredArgs(self):
        def args(*args, **stuff):
            return True

        inner = "{{direction}}"
        modInner = preppy.getModule('dummy1', savePyc=0, sourcetext=inner)
        outer = """{{for direction in directions}}{{inner.getOutput({'direction':direction})}}{{endfor}}"""
        modOuter = preppy.getModule('dummy2', savePyc=0, sourcetext=outer)
        ns = {
            'directions': ('NORTH', 'SOUTH', 'EAST', 'WEST'),
            'inner': modInner
        }
        output = modOuter.getOutput(ns)
        #self.assertRaises(NameError, modOuter.getOutput, ns)
        self.assertEqual(output, "NORTHSOUTHEASTWEST")
 def getGetOutput(self, prepCode, *args, **kwds):
     global _gcount
     mod = preppy.getModule('test_preppy%d' % _gcount,
                            savePyc=0,
                            sourcetext=prepCode)
     _gcount += 1
     return mod.get(*args, **kwds)
Beispiel #3
0
def processTest(filename, dictionary={}):
    root, ext = os.path.splitext(filename)
    outFileName = root + '.html'
    mod = preppy.getModule(root)
    outFile = open(outFileName, 'w')
    mod.run(dictionary, outputfile = outFile)
    outFile.close()
Beispiel #4
0
def generate_pdf(json_file_name, options):
    data = json.load(open(json_file_name))

    here = os.path.abspath(os.path.dirname('__file__'))
    output = os.path.abspath(options.output)
    if not os.path.isdir(output):
        os.makedirs(output, 0o755)

    data = jsondict.condJSONSafe(data)
    ns = dict(data=data,
              bb2rml=bb2rml,
              format="long" if options.longformat else "short")
    ns['RML_DIR'] = os.getcwd()
    FONT_DIR = ns['FONT_DIR'] = os.path.join(ns['RML_DIR'], 'fonts')

    for fn in os.listdir(FONT_DIR):
        print("font name:" + fn)
        pdfmetrics.registerFont(TTFont(os.path.splitext(fn)[0], fn))

    ns['RSRC_DIR'] = os.path.join(ns['RML_DIR'], 'resources')
    template = preppy.getModule('PythonInvoice.prep')
    rmlText = template.getOutput(ns, quoteFunc=preppy.stdQuote)
    file_name_root = os.path.join(
        output,
        os.path.splitext(os.path.basename(json_file_name))[0])

    if options.saverml:
        rml_file_name = file_name_root + '.rml'
        open(rml_file_name, 'w').write(rmlText)
    pdf_file_name = file_name_root + '.pdf'
    rml2pdf.go(rmlText, outputFileName=pdf_file_name)
    print('saved %s' % pdf_file_name)
Beispiel #5
0
def create_instrumentation_classes(manifest_path, package):
    logger.info('Instrumenting Java classes')

    # Get the source code directory starting from the manifest path. The source code
    # could be in a different location, here we try the most common paths.
    source_code_dir_candidates = [
        os.path.join(os.path.dirname(manifest_path), 'java',
                     *package.split('.')),
        os.path.join(os.path.dirname(manifest_path), 'src',
                     *package.split('.')),
        os.path.join(os.path.dirname(manifest_path), 'src', 'main',
                     *package.split('.')),
        # TODO: Kotlin support
        # os.path.join(os.path.dirname(manifest_path), 'kotlin', *package.split('.'))
    ]

    source_code_dir = None
    for directory in source_code_dir_candidates:
        if os.path.isdir(directory):
            source_code_dir = directory
            break

    if not source_code_dir:
        raise NotADirectoryError(
            'Impossible to find a source code directory among {0}'.format(
                source_code_dir_candidates))

    # Generating EndCoverageBroadcast
    template = preppy.getModule(
        os.path.join(SCRIPT_DIR, 'templates', 'EndCoverageBroadcast.prep'))
    my_java = template.get(package)
    with open(os.path.join(source_code_dir, 'EndCoverageBroadcast.java'),
              'w') as my_file:
        my_file.write(my_java)
Beispiel #6
0
def main():

    data_graphics_one = [[4.22], [4.12], [3.65], [3.65], [3.65], [3.65]]
    categoryNames_graphics_one = ['1', '2', '3', "4", "5", "6"]
    graphics_one = FactSheetHoldingsVBar()
    graphics_one.createGraphics(data_graphics_one, categoryNames_graphics_one,
                                "graphics_one/")

    template = preppy.getModule('example_dos.prep')

    xbrl = os.path.dirname(
        os.path.dirname(__file__)) + "/Convertidor/xbrl/Anexo5FicS2.xbrl"
    xml_label_iic_fic = os.path.dirname(os.path.dirname(
        __file__)) + "/Convertidor/xbrl/iic-fic-2009-03-31-label.xml"
    xml_label_iic_com = os.path.dirname(os.path.dirname(
        __file__)) + "/Convertidor/xbrl/iic-com-2009-03-31-label.xml"

    documento = PDFOrder(xbrl, xml_label_iic_fic, xml_label_iic_com)

    lista_elementos = documento.fechDiccionari()

    rmlText = template.get(lista_elementos)

    pdfFileName = "pdf/documento" + '.pdf'
    rml2pdf.go(rmlText, outputFileName=pdfFileName)
Beispiel #7
0
    def generate_pdf(self, data, template, save_path):
        """
            从二进制流中创建PDF并返回
            @param data  渲染XML的数据字典
            @param template 需要渲染的XML文件地址(全路径)
            @param save_file PDF文件保存的地址(全路径)
        """

        if save_path and not os.path.exists(save_path):
            file_path_array = save_path.split("/")
            save_file_dir = file_path_array[:-1]

            if not os.path.exists("/".join(save_file_dir)):
                os.makedirs("/".join(save_file_dir))

        # 读取模板文件
        empty_template = preppy.getModule(template)

        # 渲染模板文件
        render_data = {'data': data, 'static': self.statics_dir}

        # 渲染PDF页面
        render_rml = empty_template.getOutput(render_data)

        # 生成PDF
        binary_pdf = trml2pdf.parseString(render_rml)

        if save_path:
            # 保存PDF
            open(save_path, 'wb').write(binary_pdf)

        return binary_pdf
Beispiel #8
0
def gen_html(recipe_dict):

    mymodule = p.getModule(default_template)

    name = recipe_dict['name']
    ingredients = recipe_dict['ingredients']
    method = recipe_dict['method']

    html = mymodule.get(name, ingredients, method)

    return html
Beispiel #9
0
def processTest(filename, dictionary={}):
    #this ensures we search for prep files in the module
    #where this tests lives, wherever we invoked them from.
    import check_basics
    dirName = os.path.dirname(check_basics.__file__)
    #print('processTest: %r'%dictionary)
    root, ext = os.path.splitext(filename)
    outFileName = os.path.join(dirName, root + '.html')
    mod = preppy.getModule(os.path.join(dirName, root))
    outFile = open(outFileName, 'w')
    mod.run(dictionary, outputfile=outFile)
    outFile.close()
Beispiel #10
0
def pdf_rml(request):
    rml_context = dict(name='RML Test')

    template = preppy.getModule('hello.rml')
    rml = template.getOutput(rml_context)
    e = trml2pdf.parseString(rml)

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="hello.pdf"'

    response.write(e)
    return response
Beispiel #11
0
def main(argv):
    # Load the rml template into the preprocessor, ...
    template = preppy.getModule('reportTemplate.prep')
        
    # ... and do the preprocessing.
    #{{def(sensor, date, requester_name, requester_address, requester_contact, expert_name, expert_address, expert_contact, observations, plot)}}
    rmlText = template.get("Sensor 1", datetime.datetime.now().strftime("%Y-%m-%d"), "NA", "NA", "NA", "NA", "NA", "NA", "NA", "NA")
    
    # Finally generate the *.pdf output ...
    pdf = rml2pdf.parseString(rmlText)
    
    # ... and save it.
    with open('rmlReport.pdf', 'w') as pdfFile:
        pdfFile.write(pdf.read())
 def getHtml(self):
     template = preppy.getModule(self.prepFileDir + '/' + self.prepFileName)
     self.pages = []
     for student in self.result['students']:
         temp_html = template.getOutput({
             self.prepParamVar: self.result,
             'student': student
         })
         html_file = self.prepFileDir + '/' + str(student) + '.html'
         html_write = open(html_file, 'w')
         html_write.write(temp_html)
         html_write.close()
         self.pages.append(html_file)
     return self.pages
Beispiel #13
0
def create_pdf(catalog, template):
	#pdb.set_trace()
	DATA_DIR=os.path.join(RUTA_PROYECTO,"static\\data")
	RML_DIR = os.path.join(RUTA_PROYECTO,"static\\rml")
	templateName = os.path.join(RML_DIR, template)
	template = preppy.getModule(templateName)
	namespace = {
		'estudiantes':catalog,
		'RML_DIR': RML_DIR
		}
	rml = template.getOutput(namespace)
	open(os.path.join(DATA_DIR,'latest.rml'), 'w+').write(rml)
	buf = StringIO.StringIO()
	rml2pdf.go(rml, outputFileName=buf)
	return buf.getvalue()
def create_pdf(catalog, template):
    """Creates PDF as a binary stream in memory, and returns it

    This can then be used to write to disk from management commands or crons,
    or returned to caller via Django views.
    """
    RML_DIR = 'rml'
    templateName = os.path.join(RML_DIR, template)
    template = preppy.getModule(templateName)
    namespace = {'products': catalog, 'RML_DIR': RML_DIR, 'IMG_DIR': 'img'}
    rml = template.getOutput(namespace)
    open(os.path.join(DATA_DIR, 'latest.rml'), 'w').write(rml)
    buf = getBytesIO()
    rml2pdf.go(asBytes(rml), outputFileName=buf)
    return buf.getvalue()
Beispiel #15
0
def build_pdf(heading, inventory, template):

    #RML_DIR = 'rml'
    templateName = os.path.join(RML_DIR, template)
    template = preppy.getModule(templateName)
    namespace = {
        'heading':heading,
        'products':inventory,
        'RML_DIR': RML_DIR
        }

    rml = template.getOutput(namespace)
    open(os.path.join(RML_DIR,'latest.rml'), 'w').write(rml)
    buf = BytesIO()
    rml2pdf.go(rml, outputFileName=buf)
    return buf.getvalue()
Beispiel #16
0
 def getHtml(self):
     template = preppy.getModule(self.prepFileDir + '/' + self.prepFileName)
     self.pages = []
     self.calculateTotalMarks()
     for student in self.result['students']:
         for subject in student['subjects']:
             temp_html = template.getOutput({
                 self.prepParamVar: subject,
                 'studentId': student['id']
             })
             html_file = self.prepFileDir + '/' + str(
                 student['id']) + '-' + str(subject['id']) + '.html'
             html_write = open(html_file, 'w')
             html_write.write(temp_html)
             html_write.close()
             self.pages.append(html_file)
     return self.pages
Beispiel #17
0
def main(argv):
    # Load the rml template into the preprocessor, ...
    template = preppy.getModule('testDoc.prep')

    # ... fetch the table data ...
    table = fetchTable()

    # ... and do the preprocessing.
    rmlText = template.get(
        datetime.datetime.now().strftime("%Y-%m-%d"), 'Andreas Wilhelm',
        'www.avedo.net', '*****@*****.**', table)

    # Finally generate the *.pdf output ...
    pdf = rml2pdf.parseString(rmlText)

    # ... and save it.
    with open('rmlReport.pdf', 'w') as pdfFile:
        pdfFile.write(pdf.read())
Beispiel #18
0
def create_pdf(catalog, template):
    """Creates PDF as a binary stream in memory, and returns it

    This can then be used to write to disk from management commands or crons,
    or returned to caller via Django views.
    """
    RML_DIR = 'rml'
    templateName = os.path.join(RML_DIR, template)
    template = preppy.getModule(templateName)
    namespace = {
        'products':catalog,
        'RML_DIR': RML_DIR
        }
    rml = template.getOutput(namespace)
    open(os.path.join(DATA_DIR,'latest.rml'), 'w').write(rml)
    buf = StringIO.StringIO()
    rml2pdf.go(rml, outputFileName=buf)
    return buf.getvalue()
Beispiel #19
0
  def __init__(self, parent = None):
    ''' '''
    super(Ui_WidgetReport, self).__init__()
    self.__parentWidget = parent
    self.helper = Ui_WidgetReportHelper(self)

    self.cosmos_cli = CosmosClient()
    
    #TODO: these should be in the app configuration tool
    webhdfs_url = 'http://130.206.80.46:14000/webhdfs/v1'
    auth_url = 'https://130.206.80.46:13000/cosmos-auth/v1'
    local_filepath = os.environ['HOME']+os.sep+'.fresh'+os.sep+'history'
    username = '******'
    password = '******'
    cosmos_user = '******'
    serv = 'NA'
    servpath = 'NA'
    #--------------------------
    
    #Tuple(sensor_type, sensor_name)
    self.sensor_list = [#'sensor', 'sensor_1'), 
                        #('sensor', 'sensor_2'), 
                        #('sensor', 'sensor_3'), 
                        #('sensor', 'sensor_4'), 
                        #('sensor', 'sensor_5'),
                        #('sensor', 'sensor_6'),
                        #('sensor', 'sensor_7'),
                        #('sensor', 'sensor_8'),
                        ('sensor', 'sensor_9'),
                        ('sensor', 'sensor_10')] 
    
    self.entity_list = dict()
    
    self.cosmos_cli.username = username
    self.cosmos_cli.password = password
    self.cosmos_cli.webhdfs_url = webhdfs_url
    self.cosmos_cli.auth_url = auth_url
    self.cosmos_cli.hdfs_username = cosmos_user
    self.cosmos_cli.hdfs_filepath = '/'+serv+'_serv/'+servpath+'_servpath/'
    self.cosmos_cli.local_filepath = local_filepath
    
    self.rep_template = preppy.getModule('reportTemplate.prep')
    
    self.setupUi(self)
Beispiel #20
0
def create_fund_report():
    template_file = preppy.getModule(os.path.join(RML_DIR, 'report.prep'))
    context = {}
    context['name'] = '<span>Syed Saqlain</span>'
    context['company'] = 'Gale Creative Agency Pvt Ltd'
    context['RML_DIR'] = RML_DIR
    context['RML_STATIC_DIR'] = RML_STATIC_DIR
    context['line_chart_data'] = get_line_chart_data()
    context['line_plot_data'] = get_line_plot_data()
    context['bar_chart_categories'] = get_bar_chart_data()['categories']
    context['bar_chart_values'] = get_bar_chart_data()['values']
    context['pie_chart_labels'] = get_pie_chart_data()['labels']
    context['pie_chart_data'] = get_pie_chart_data()['data']
    rml = template_file.getOutput(context)

    buf = StringIO.StringIO()
    rml2pdf.go(rml, outputFileName=buf)

    return buf.getvalue()
Beispiel #21
0
def main():
    data = "names.csv"

    with open(data) as a:
        reader = csv.reader(a)
        template = preppy.getModule("ex14.prep")

        for row in reader:
            name = row[0]
            location = row[1]

            rmltext = template.get(name, location)

            pdfFileName = name + ".pdf"
            rml2pdf.go(rmltext, outputFileName=pdfFileName)

            print("Guardado {}".format(pdfFileName))

    a.close()
Beispiel #22
0
    def generate_binary_pdf(self, data, template):
        """
            从二进制流中创建PDF并返回
            @param data  渲染XML的数据字典
            @param template 需要渲染的XML文件地址(全路径)
        """

        # 读取模板文件
        pdf_template = preppy.getModule(template)

        # 渲染模板文件
        render_data = {'data': data, 'static': self.statics_path}

        # 渲染PDF页面
        char_rml = pdf_template.getOutput(render_data)

        # 生成PDF
        pdf_binary = trml2pdf.parseString(char_rml)

        return pdf_binary
    def getRunTimeOutput(self,
                         prepCode,
                         quoteFunc=str,
                         lquoteFunc=None,
                         **params):
        "compile code, run with parameters and collect output"

        global _gcount
        mod = preppy.getModule('test_preppy%d' % _gcount,
                               savePyc=0,
                               sourcetext=prepCode)
        _gcount += 1

        collector = []
        mod.run(params,
                __write__=collector.append,
                quoteFunc=quoteFunc,
                lquoteFunc=lquoteFunc)
        output = (quoteFunc or lquoteFunc)('')[0:0].join(collector)
        return output
    def checkOutputModes(self):
        "compile code, run with parameters and collect output"
        prepCode = "Hello, my name is {{name}} and I am a " \
                   "{{if sex=='m'}}guy{{elif sex=='f'}}gal{{else}}neuter{{endif}}."

        params = {'name': 'fred', 'sex': 'm'}

        mod = preppy.getModule('test_preppy', savePyc=0, sourcetext=prepCode)

        # this way of making a module should work back to 1.5.2
        # nowadays 'new.module' would be preferable for clarity

        # use write function
        collector = []
        mod.run(params, __write__=collector.append)
        output1 = ''.join(collector)
        from preppy import StringIO
        buf = StringIO()
        mod.run(params, outputfile=buf)
        output2 = buf.getvalue()
        assert output1 == output2, '__write__ and outputfile results differ'

        output3 = mod.getOutput(params)
        assert output3 == output2, 'getOutput(...) and outputfile results differ'
from z3c.rml import rml2pdf
import preppy

template_recibo = preppy.getModule('template_recibo.prep')
template_orden_pago = preppy.getModule('template_orden_pago.prep')


#Traer cada modulo de datos
#rmlText = template.get("Martin Di Lisio", "Canada 1248 (7000) Tandil", ['uno', 'dos'])
#rmlText = template.get("Martin Di Lisio","Martin Di Lisio","Martin Di Lisio","Martin Di Lisio", "Canada 1248 (7000) Tandil", 'Exento', '20-28232105-0', '1111111','2222')

"""
#Convertimos el xml a pdf. parseString nos retorna un StringIO
out = rml2pdf.parseString(rmlText)
pdf = open("elpdf.pdf", "wb")
pdf.write(out.read())
"""
Beispiel #26
0
    def check07NoOutputFile(self):
        sourceString = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
        <HTML>
        <HEAD>
        <TITLE>ReportLab Preppy Test Suite 007</TITLE>
        </HEAD>

        <BODY>
        <FONT COLOR=#000000>
        <TABLE BGCOLOR=#0000CC BORDER=0 CELLPADDING=0 CELLSPACING=0 WIDTH=100%>
        <TR>
        <TD>
        <FONT COLOR=#FFFFFF>
        <CENTER>
        <H1>Preppy Test 007 - Creating A Module Without Using The Filesystem</H1>
        </CENTER>
        </FONT>
        </TD>
        </TR>
        </TABLE>

        <BR>

        This test creates a preppy source module in memory. It does <I>not</I> have a preppy source file (a file ending in '.prep')

        <H2>Expected Output</H2>
        <P>

        Below is a listing of the files in the same directory as this HTML file. There should be no file called <I>sample007.prep</I>.


        <BR><HR>
        <BR><CENTER>
        <TABLE>
        {{script}}
        import os
        leftColumn = []
        rightColumn = []

        fileList = os.listdir(os.getcwd())

        for item in range(0,len(fileList),2):
            if os.path.isfile(fileList[item]):
                leftColumn.append(fileList[item])

        for item in range(1,len(fileList)-1,2):
            if os.path.isfile(fileList[item]):
                rightColumn.append(fileList[item])

        for loopCounter in range(0, len(leftColumn)):
            __write__("<TR><TD WIDTH=30%>")
            __write__(leftColumn[loopCounter])
            __write__("</TD>")
            __write__("<TD WIDTH=30%>")
            try:
                __write__(rightColumn[loopCounter])
                __write__("</TD></TR>")
            except:
                __write__(" ")
                __write__("</TD></TR>")
                {{endscript}}
        </TD></TR>
        </TABLE>
        </CENTER>

        <BR>
        <HR>

        </FONT>
        </BODY>
        </HTML>"""

        mod = preppy.getModule("dummy_module", sourcetext=sourceString)
        modDataList = []
        tempDict = {'temp': 'temporary variable'}

        # this way it goes to the string
        #from reportlab.lib.utils import getStringIO
        #f = getStringIO()
        #mod.run(tempDict, outputfile=f)
        #f.seek(0)
        #output = f.read()

        #this way it goes to the list and also gets printed
        mod.run(tempDict, __write__=modDataList.append)
        #print('length of list is %d' % len(modDataList))
        output = ''.join(modDataList)
        outFile = open('sample007.html', 'w')
        outFile.write(output)
        outFile.close()
Beispiel #27
0
 def check06NoPythonFile(self):
     mod = preppy.getModule(os.path.join(self.dirName, 'sample006'),
                            savefile=0)
     outFile = open(os.path.join(self.dirName, 'sample006.html'), 'w')
     mod.run(dictionary={}, outputfile=outFile)
     outFile.close()
 def checkUnicodeSourceText(self):
     mod = preppy.getModule('./test_preppy',
                            savePyc=0,
                            sourcetext=u'Hello World')
Beispiel #29
0
def run():
    from preppy import getModule
    module = getModule("newstyle.prep", verbose=1)
    print(
        module.get([('fred', 'm'), ('bill', 'f'), ('bacterium', 'other'),
                    ('jill', 'm')]))
# .............................................................................
# by student

for cwid,info in students.students.items():
    if 'name' not in info: continue

    name = students.students[cwid]['alias'].lower()
    html = os.path.join(htmlbuilddir, name + '.html')
    pdf = os.path.join(pdfbuilddir, name + '.pdf')

    with open(html, 'w') as f:
        f.write(
            preppy.getModule(
                'gen-grade-sheet--student.html.preppy',
                source_extension='.preppy',
                savePyc=0
            ).get(cwid, grades, standards, students)
        )

    if arg in ( 'pdf', ):
        sp = subprocess.Popen( "wkhtmltopdf '" + html + "' '" + pdf + "'",
                               shell = True,
                               stdout = subprocess.DEVNULL,
                               stderr = subprocess.DEVNULL,
                               universal_newlines = True )
        sp.communicate()

# .............................................................................
# by section
Beispiel #31
0
os.makedirs(pdfbuilddir)

# .............................................................................
# by student

for cwid, info in students.students.items():
    if 'name' not in info: continue

    name = students.students[cwid]['alias'].lower()
    html = os.path.join(htmlbuilddir, name + '.html')
    pdf = os.path.join(pdfbuilddir, name + '.pdf')

    with open(html, 'w') as f:
        f.write(
            preppy.getModule('gen-grade-sheet--student.html.preppy',
                             source_extension='.preppy',
                             savePyc=0).get(cwid, grades, standards, students))

    if arg in ('pdf', ):
        sp = subprocess.Popen("wkhtmltopdf '" + html + "' '" + pdf + "'",
                              shell=True,
                              stdout=subprocess.DEVNULL,
                              stderr=subprocess.DEVNULL,
                              universal_newlines=True)
        sp.communicate()

# .............................................................................
# by section

titles = ['all'] + [
    s.name.split('.')[0] for s in os.scandir(titandir)
Beispiel #32
0
def generatePdf(request, cattle_id):
    # Load the rml template into the preprocessor, ...
    template = preppy.getModule('testDoc.prep')
    user = request.user
    farm = Ganaderia.objects.get(perfil=user)
    cattle = Ganado.objects.get(id=cattle_id)
    configuration = Configuracion.objects.get(id=farm.configuracion.id)
    if configuration.tipo_identificacion == 'simple':
        nombre = cattle.identificacion_simple.nombre
        rp = cattle.identificacion_simple.rp
        raza = cattle.get_raza_display()
        nacimiento = str(cattle.nacimiento)
        concepcion = cattle.get_forma_concepcion_display()
        edad = str(cattle.edad_anios) + ' años, ' + str(
            cattle.edad_meses) + ' meses y ' + str(cattle.edad_dias) + ' dias'
        try:
            cattle_mother = Ganado.objects.get(identificacion_simple__rp=cattle
                                               .identificacion_simple.rp_madre)
            cattle_mother = cattle_mother.identificacion_simple.nombre
        except ObjectDoesNotExist:
            cattle_mother = 'Madre Desconocida'
        try:
            cattle_father = Ganado.objects.get(identificacion_simple__rp=cattle
                                               .identificacion_simple.rp_padre)
            cattle_father = cattle_father.identificacion_simple.nombre
        except ObjectDoesNotExist:
            try:
                cattle_father = Insemination.objects.get(
                    rp=cattle.identificacion_simple.rp_padre)
                cattle_father = cattle_father.name
            except ObjectDoesNotExist:
                cattle_father = 'Padre Desconocido'
        celos = cattle.celos.count()
        problem_gestacion = ProblemaGestacion.objects.filter(id=cattle.id)
        total_births = Gestacion.objects.filter(
            Q(ganado=cattle, is_active=False)
            & ~Q(problema=problem_gestacion)).count()
        total_problems_births = ProblemaGestacion.objects.filter(
            id=cattle.id).count()
        ordenio = Ordenio.objects.filter(ganado=cattle)
        count_milk = 0
        count = 0
        for o in ordenio:
            if o.numero_ordenio == configuration.numero_ordenios:
                count_milk += o.total
                count += 1
        if count_milk > 0:
            count_milk = count_milk / count

        application_food = ApplicationFood.objects.filter(cattle=cattle)
        food = []
        i = 1
        for f in application_food:
            aux = str(f.food.name + ' - ' + str(f.food.consumer_amount) + ' ' +
                      f.food.get_unit_display() + '. (X' + str(i) + ')')
            if aux not in food:
                food.append(aux)
            else:
                index = food.index(aux)
                i += 1
                food[index] = str(f.food.name + ' - ' +
                                  str(f.food.consumer_amount) + ' ' +
                                  f.food.get_unit_display() +
                                  '.') + ' (X' + str(i) + ')'
        medicament_wormer = Medicament.objects.filter(farm=farm,
                                                      is_wormer=True)
        application_medicament_wormer = ApplicationMedicament.objects.filter(
            medicament=medicament_wormer, cattle=cattle).order_by('medicament')
        wormer = []
        i = 1
        for w in application_medicament_wormer:
            aux = str(w.medicament.name + ' - ' +
                      str(w.medicament.amount_application) + ' ' +
                      w.medicament.get_unit_display() + '. (X' + str(i) + ')')
            if aux not in wormer:
                wormer.append(aux)
            else:
                index = wormer.index(aux)
                i += 1
                wormer[index] = str(w.medicament.name + ' - ' +
                                    str(w.medicament.amount_application) +
                                    ' ' + w.medicament.get_unit_display() +
                                    '.') + ' (X' + str(i) + ')'
        medicament_vaccine = Medicament.objects.filter(farm=farm,
                                                       is_vaccine=True)
        application_medicament_vaccine = ApplicationMedicament.objects.filter(
            medicament=medicament_vaccine,
            cattle=cattle).order_by('medicament')
        vaccine = []
        i = 1
        for v in application_medicament_vaccine:
            aux = str(v.medicament.name + ' - ' +
                      str(v.medicament.amount_application) + ' ' +
                      v.medicament.get_unit_display() + '. (X' + str(i) + ')')
            if aux not in vaccine:
                vaccine.append(aux)
            else:
                index = vaccine.index(aux)
                i += 1
                vaccine[index] = str(v.medicament.name + ' - ' +
                                     str(v.medicament.amount_application) +
                                     ' ' + v.medicament.get_unit_display() +
                                     '.') + ' (X' + str(i) + ')'

    else:
        nombre = cattle.identificacion_ecuador.nombre
        rp = cattle.identificacion_ecuador.rp
        raza = cattle.get_raza_display()
        nacimiento = str(cattle.nacimiento)
        concepcion = cattle.get_forma_concepcion_display()
        edad = str(cattle.edad_anios) + ' años, ' + str(
            cattle.edad_meses) + ' meses y ' + str(cattle.edad_dias) + ' dias'
        try:
            cattle_mother = Ganado.objects.get(
                identificacion_ecuador__rp=cattle.identificacion_ecuador.
                rp_madre)
            cattle_mother = cattle_mother.identificacion_ecuador.nombre
        except ObjectDoesNotExist:
            cattle_mother = 'Madre Desconocida'
        try:
            cattle_father = Ganado.objects.get(
                identificacion_ecuador__rp=cattle.identificacion_ecuador.
                rp_padre)
            cattle_father = cattle_father.identificacion_ecuador.nombre
        except ObjectDoesNotExist:
            try:
                cattle_father = Insemination.objects.get(
                    rp=cattle.identificacion_ecuador.rp_padre)
                cattle_father = cattle_father.name
            except ObjectDoesNotExist:
                cattle_father = 'Padre Desconocido'
        celos = cattle.celos.count()
        problem_gestacion = ProblemaGestacion.objects.filter(id=cattle.id)
        total_births = Gestacion.objects.filter(
            Q(ganado=cattle, is_active=False)
            & ~Q(problema=problem_gestacion)).count()
        total_problems_births = ProblemaGestacion.objects.filter(
            id=cattle.id).count()
        ordenio = Ordenio.objects.filter(ganado=cattle)
        count_milk = 0
        count = 0
        for o in ordenio:
            if o.numero_ordenio == configuration.numero_ordenios:
                count_milk += o.total
                count += 1
        if count_milk > 0:
            count_milk = count_milk / count
        application_food = ApplicationFood.objects.filter(cattle=cattle)
        food = []
        i = 1
        for f in application_food:
            aux = str(f.food.name + ' - ' + str(f.food.consumer_amount) + ' ' +
                      f.food.get_unit_display() + '. (X' + str(i) + ')')
            if aux not in food:
                food.append(aux)
            else:
                index = food.index(aux)
                i += 1
                food[index] = str(f.food.name + ' - ' +
                                  str(f.food.consumer_amount) + ' ' +
                                  f.food.get_unit_display() +
                                  '.') + ' (X' + str(i) + ')'
        medicament_wormer = Medicament.objects.filter(farm=farm,
                                                      is_wormer=True)
        application_medicament_wormer = ApplicationMedicament.objects.filter(
            medicament=medicament_wormer, cattle=cattle).order_by('medicament')
        wormer = []
        i = 1
        for w in application_medicament_wormer:
            aux = str(w.medicament.name + ' - ' +
                      str(w.medicament.amount_application) + ' ' +
                      w.medicament.get_unit_display() + '. (X' + str(i) + ')')
            if aux not in wormer:
                wormer.append(aux)
            else:
                index = wormer.index(aux)
                i += 1
                wormer[index] = str(w.medicament.name + ' - ' +
                                    str(w.medicament.amount_application) +
                                    ' ' + w.medicament.get_unit_display() +
                                    '.') + ' (X' + str(i) + ')'

    # ... and do the preprocessing.
    table = []
    # date, name, website, email, description, farm, adress, table
    rmlText = template.get(
        table,
        datetime.datetime.now().strftime("%Y-%m-%d"),
        'Reporte Individual de Ganado', 'www.hatosganaderos.com',
        '*****@*****.**',
        'HatosGanaderos te ayuda con el control y organización de reproducción, alimentación, sanidad y producción de toda tu entidad ganadera.',
        'Ganadería Lojana', 'Ciudadela universitaria', nombre, rp, raza,
        nacimiento, concepcion, edad, cattle_mother, cattle_father, celos,
        total_births, total_problems_births, count_milk, food, wormer, vaccine)

    # Finally generate the *.pdf output ...
    pdf = rml2pdf.parseString(rmlText)

    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(pdf, content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="somefilename.pdf"'

    return response
Beispiel #33
0
def build_loaders_for_all_locales():
    """builds a different loader script for each locale. If you want to add one, add it to the supported_locales array above."""
    for locale in supported_locales:
        with open("m32cmploader_{}.js".format(locale), "w+") as f:
            f.write(preppy.getModule("cmp_loader.prep").get(locale))
Beispiel #34
0
def main(t,d1,d2,d3,d4,d5,d6,d7,e76,e78,e79,res_alert,n_alert,disk_table):
	template = preppy.getModule('/home/mmport/sh/python/daily.prep')
	rmlText = template.get(t,d1,d2,d3,d4,d5,d6,d7,e76,e78,e79,res_alert,n_alert,disk_table)
	pdfFilename = "/home/mmport/zabbix/www/csv/%s_daily.pdf"%t
	rml2pdf.go(rmlText, outputFileName=pdfFilename)
def generate_pdf(json_file_name, options):
    data = json.load(open(json_file_name))

    here = os.path.abspath(os.path.dirname('__file__'))
    output = os.path.abspath(options.output)
    if not os.path.isdir(output):
        os.makedirs(output,0o755)

    #wrap it up in something friendlier
    data = jsondict.condJSONSafe(data)

    #make a dictionary to pass into preppy as its namespace.
    #you could pass in any Python objects or variables,
    #as long as the template expressions evaluate
    ns = dict(data=data, bb2rml=bb2rml, format="long" if options.longformat else "short")

    #we usually put some standard things in the preppy namespace
    ns['DATE_GENERATED'] = datetime.date.today()
    ns['showBoundary'] = "1" if options.showBoundary else "0"

    #let it know where it is running; trivial in a script, confusing inside
    #a big web framework, may be used to compute other paths.  In Django
    #this might be relative to your project path,
    ns['RML_DIR'] = os.getcwd()     #os.path.join(settings.PROJECT_DIR, appname, 'rml')

    #we tend to keep fonts in a subdirectory.  If there won't be too many,
    #you could skip this and put them alongside the RML
    FONT_DIR = ns['FONT_DIR'] = os.path.join(ns['RML_DIR'], 'fonts')


    #directory for images, PDF backgrounds, logos etc relating to the PDF
    ns['RSRC_DIR'] = os.path.join(ns['RML_DIR'], 'resources')

    #We tell our template to use Preppy's standard quoting mechanism.
    #This means any XML characters (&, <, >) will be automatically
    #escaped within the prep file.
    template = preppy.getModule('rml/factsheet.prep')
    

    #this hack will allow rmltuils functions to 'know' the default quoting mechanism
    #try:
    #   import builtins as __builtin__
    #except:
    #   import __builtin__
    #__builtin__._preppy_stdQuote = preppy.stdQuote
    rmlText = template.getOutput(ns, quoteFunc=preppy.stdQuote)

    file_name_root = os.path.join(output,os.path.splitext(os.path.basename(json_file_name))[0])
    if options.saverml:
        #It's useful in development to save the generated RML.
        #If you generate some illegal RML, pyRXP will complain
        #with the exact line number and you can look to see what
        #went wrong.  Once running, no need to save.  Within Django
        #projects we usually have a settings variable to toggle this
        #on and off.
        rml_file_name = file_name_root + '.rml'
        open(rml_file_name, 'w').write(rmlText)
    pdf_file_name = file_name_root + '.pdf'

    #convert to PDF on disk.  If you wanted a PDF in memory,
    #you could pass a StringIO to 'outputFileName' and
    #retrieve the PDF data from it afterwards.
    rml2pdf.go(rmlText, outputFileName=pdf_file_name)
 def checkUnicodeDirectory(self):
     mod = preppy.getModule('./test_preppy',
                            directory=u'.',
                            savePyc=0,
                            sourcetext='Hello World')
 def checkUnicodeExtension(self):
     mod = preppy.getModule('./test_preppy',
                            source_extension=u'.prep',
                            savePyc=0,
                            sourcetext='Hello World')
 def getRunTimeOutput(self, prepCode, *args, **kwds):
     "compile code, run with parameters and collect output"
     mod = preppy.getModule('test_preppy', savePyc=0, sourcetext=prepCode)
     return mod.get(*args, **kwds)
 def checkUnicodeName(self):
     mod = preppy.getModule(u'./test_preppy',
                            savePyc=0,
                            sourcetext='Hello World')
    def generatePDF(self):

        class SampleData:
            pass

        samples = search.findall_by_attr(self.configTree, True, name = "selected", maxlevel=2)
        samples = samples[1:] #Skip root

        sample_list = []
        for s in samples:
            class ParamData:
                pass
            if s.sampleType == "SNP":
                freq_title = f"Freq({s.sample.freq_unit})"

                sd = SampleData()
                sd.type = "SNP"
                sd.name = s.sample.name
                sd.freq =  s.sample.freq
                sd.freq_unit = s.sample.freq_unit
                
                sd.testFreq = np.ceil(np.geomspace(np.ceil(sd.freq[0]), np.ceil(sd.freq[-1]), 13, endpoint=True)).astype(int)

                params = search.findall_by_attr(s, True, name = "selected", maxlevel=2)
                params = params[1:] #Skip root
                param_list = []
                for p in params:

                    pd = ParamData()
                    param_name = p.name
                    pd.name = param_name 

                    series = search.findall_by_attr(p , True, name = "selected", maxlevel=2)
                    series = series[1:] #Skip root

                    series_list = []
                    class LineData:
                        pass
                    
                    pd.testPoints = {'freq': sd.testFreq}
                    pd.worst_margin = {}
                    pd.standard = None
                    for line in series:
                        ld = LineData()
                        line_name = line.name  #pair
                        ld.name = line_name
                        

                        if line_name == "Limit":
                            try:
                                lim = s.sample.standard.limits[param_name.replace(' ', '')].getArray()
                                worst, pd.pass_fail  = s.sample.getWorstMargin(param_name.replace(' ', ''))
                                #print(worst)
                                for key, (value, freq, limit, worstMargin) in worst.items():
                                    pd.worst_margin[key] = (np.around(float(freq), decimals = 3), np.around(float(worstMargin, decimals=3)))
                                    pd.standard = s.sample.standard.name
                                f, points = zip(*lim)
                                #print(points)
                                points = np.array(points, dtype=np.float16)
                            except Exception as e:
                                print("FAIL on LIMIT : ", param_name, e)
                        else:
                            points = s.sample.getParam(param_name)[line_name]
                        pd.testPoints[line_name] = np.around(self.getTestPoints(sd.freq, points, desiredFreqs=sd.testFreq), decimals=3)

                        series_list.append(ld)
                    pd.lines = series_list
                    param_list.append(pd)

                sd.params = param_list
                sample_list.append(sd)

                try:
                    print("sample name : ", s.sample.name)
                except Exception as e:
                    print(e)

        template = "graphs_report.prep"
        RML_DIR = "templates"
        DATA_DIR = os.path.join(RML_DIR, "data")
        output = self.outputFile
        templateName = os.path.join(RML_DIR, template)
        template = preppy.getModule(templateName)
        namespace = {
            'samples': sample_list,
            'filename' : ntpath.basename(output),
            'RML_DIR': RML_DIR,
            'IMG_DIR': 'img'
            }
        rml = template.getOutput(namespace)
        open(os.path.join(DATA_DIR,'latest.rml'), 'w').write(rml)
        #print(rml)
        buf = getBytesIO()
        rml2pdf.go(asBytes(rml), outputFileName=output)
        #buf = trml2pdf.parseString(asBytes(rml))
        print("PDF exported - ", ntpath.basename(output))
 def GeneratePkg( self, target = None, source = None, env = None ):
     """ SCons Command to generate PKG file
     @param target: Contains the pkg filename
     """
     pkgfilename = target[0].path
     package = self.pkg_sis[pkgfilename]
     files = self.Package( package )
     pkgargs = self.PackageArgs( package )
     
     template = self.pkg_template.get(pkgfilename, None)
             
     if template is not None:
         import preppy # Import here. Slow so imported only if needed.
         
         # Get contents if file
         if os.path.isfile(template):
             print( "scons: Reading preppy template '%s'" % template )
             f=open(template,'rb')
             template = f.read();
             f.close()                
         
         m = preppy.getModule("pkg", sourcetext=template)
         outputfile = open( pkgfilename, 'wb')
         
         data = {}
         data["files"] = files
         data.update( pkgargs )
         print( "scons: Generating pkg '%s' from preppy template " % pkgfilename )
         m.run( data, outputfile = outputfile )
         return
             
     # TODO: Use preppy here as well with default template     
     print "Creating pkg", pkgfilename        
     f = open( pkgfilename, 'w' )
                          
     if type( pkgargs["uid"] ) != str:
         pkgargs["uid"] = hex( pkgargs["uid"] ).replace("L","")
     
     version = pkgargs["version"]
     
     header = '#{"%(appname)s"},(%(uid)s),' % ( pkgargs )
     header += '%s,%s,%s' % tuple( version )
     #header += ',TYPE=%s\n\n' % pkgargs.get( "type", "" )
     header += "\n"
     
     f.write( ";Localised package name\n" )
     f.write( header )
     
     f.write( ";Localized vendor name\n" )
     f.write( '%%{"%s"}\n\n' % pkgargs.get( "vendor", "VENDOR" ) )
     
     f.write( ';Unique Vendor name\n' )
     f.write( ':"%s"\n\n' % pkgargs.get( "vendor_id", "VENDOR" ) )
     
     ## TODO: Correct UID for UIQ    
     f.write( '[0x101F7961], 0, 0, 0, {"Series60ProductID"}\n\n' )
     keys = files.keys();keys.sort()
     for x in keys:
         t = files[x]
         # Do split in platform independent way
         t = t.replace("\\","/").split( "/" )
         if t[0] == "any":
             t[0] = "!:"
         else:
             t[0] = t[0] + ":"
         # Convert the slashes for pkg
         t = "\\".join( t ).replace( "/", "\\" )            
         
         #import pdb;pdb.set_trace()
         x = relpath( os.getcwd(), x )
         x = x.replace( "/", "\\" )
         
         f.write( '%-50s - "%s"\n' % ( '"%s"' % x, t ) )
     
     f.close()
Beispiel #42
0
def generatePdf(request, cattle_id):
    # Load the rml template into the preprocessor, ...
    template = preppy.getModule('testDoc.prep')
    user = request.user
    farm = Ganaderia.objects.get(perfil=user)
    cattle = Ganado.objects.get(id=cattle_id)
    configuration = Configuracion.objects.get(id=farm.configuracion.id)
    if configuration.tipo_identificacion=='simple':
        nombre = cattle.identificacion_simple.nombre
        rp = cattle.identificacion_simple.rp
        raza = cattle.get_raza_display()
        nacimiento = str(cattle.nacimiento)
        concepcion = cattle.get_forma_concepcion_display()
        edad = str(cattle.edad_anios)+' años, '+str(cattle.edad_meses)+' meses y '+str(cattle.edad_dias)+' dias'
        try:
            cattle_mother = Ganado.objects.get(identificacion_simple__rp=cattle.identificacion_simple.rp_madre)
            cattle_mother = cattle_mother.identificacion_simple.nombre
        except ObjectDoesNotExist:
            cattle_mother = 'Madre Desconocida'
        try:
            cattle_father = Ganado.objects.get(identificacion_simple__rp=cattle.identificacion_simple.rp_padre)
            cattle_father = cattle_father.identificacion_simple.nombre
        except ObjectDoesNotExist:
            try:
                cattle_father = Insemination.objects.get(rp=cattle.identificacion_simple.rp_padre)
                cattle_father= cattle_father.name
            except ObjectDoesNotExist:
                cattle_father='Padre Desconocido'
        celos = cattle.celos.count()
        problem_gestacion=ProblemaGestacion.objects.filter(id=cattle.id)
        total_births = Gestacion.objects.filter(
                Q(ganado=cattle, is_active=False) &
                ~Q(problema=problem_gestacion)
                ).count()
        total_problems_births=ProblemaGestacion.objects.filter(id=cattle.id).count()
        ordenio = Ordenio.objects.filter(ganado=cattle)
        count_milk=0
        count=0
        for o in ordenio:
            if o.numero_ordenio == configuration.numero_ordenios:
                count_milk+=o.total
                count+=1
        if count_milk > 0:
            count_milk=count_milk/count

        application_food=ApplicationFood.objects.filter(cattle=cattle)
        food=[]
        i=1
        for f in application_food:
            aux = str(f.food.name+' - '+str(f.food.consumer_amount)+' '+f.food.get_unit_display()+'. (X'+str(i)+')')
            if aux not in food:
                food.append(aux)
            else:
                index=food.index(aux)
                i+=1
                food[index]=str(f.food.name+' - '+str(f.food.consumer_amount)+' '+f.food.get_unit_display()+'.')+' (X'+str(i)+')'
        medicament_wormer=Medicament.objects.filter(farm=farm, is_wormer=True)
        application_medicament_wormer=ApplicationMedicament.objects.filter(medicament=medicament_wormer, cattle=cattle).order_by('medicament')
        wormer=[]
        i=1
        for w in application_medicament_wormer:
            aux=str(w.medicament.name+' - '+str(w.medicament.amount_application)+' '+w.medicament.get_unit_display()+'. (X'+str(i)+')')
            if aux not in wormer:
                wormer.append(aux)
            else:
                index=wormer.index(aux)
                i+=1
                wormer[index]=str(w.medicament.name+' - '+str(w.medicament.amount_application)+' '+w.medicament.get_unit_display()+'.')+' (X'+str(i)+')'
        medicament_vaccine=Medicament.objects.filter(farm=farm, is_vaccine=True)
        application_medicament_vaccine=ApplicationMedicament.objects.filter(medicament=medicament_vaccine, cattle=cattle).order_by('medicament')
        vaccine=[]
        i=1
        for v in application_medicament_vaccine:
            aux=str(v.medicament.name+' - '+str(v.medicament.amount_application)+' '+v.medicament.get_unit_display()+'. (X'+str(i)+')')
            if aux not in vaccine:
                vaccine.append(aux)
            else:
                index=vaccine.index(aux)
                i+=1
                vaccine[index]=str(v.medicament.name+' - '+str(v.medicament.amount_application)+' '+v.medicament.get_unit_display()+'.')+' (X'+str(i)+')'

    else:
        nombre = cattle.identificacion_ecuador.nombre
        rp = cattle.identificacion_ecuador.rp
        raza = cattle.get_raza_display()
        nacimiento = str(cattle.nacimiento)
        concepcion = cattle.get_forma_concepcion_display()
        edad = str(cattle.edad_anios)+' años, '+str(cattle.edad_meses)+' meses y '+str(cattle.edad_dias)+' dias'
        try:
            cattle_mother = Ganado.objects.get(identificacion_ecuador__rp=cattle.identificacion_ecuador.rp_madre)
            cattle_mother = cattle_mother.identificacion_ecuador.nombre
        except ObjectDoesNotExist:
            cattle_mother = 'Madre Desconocida'
        try:
            cattle_father = Ganado.objects.get(identificacion_ecuador__rp=cattle.identificacion_ecuador.rp_padre)
            cattle_father = cattle_father.identificacion_ecuador.nombre
        except ObjectDoesNotExist:
            try:
                cattle_father = Insemination.objects.get(rp=cattle.identificacion_ecuador.rp_padre)
                cattle_father= cattle_father.name
            except ObjectDoesNotExist:
                cattle_father='Padre Desconocido'
        celos = cattle.celos.count()
        problem_gestacion=ProblemaGestacion.objects.filter(id=cattle.id)
        total_births = Gestacion.objects.filter(
                Q(ganado=cattle, is_active=False) &
                ~Q(problema=problem_gestacion)
                ).count()
        total_problems_births=ProblemaGestacion.objects.filter(id=cattle.id).count()
        ordenio = Ordenio.objects.filter(ganado=cattle)
        count_milk=0
        count=0
        for o in ordenio:
            if o.numero_ordenio == configuration.numero_ordenios:
                count_milk+=o.total
                count+=1
        if count_milk > 0:
            count_milk=count_milk/count
        application_food=ApplicationFood.objects.filter(cattle=cattle)
        food=[]
        i=1
        for f in application_food:
            aux = str(f.food.name+' - '+str(f.food.consumer_amount)+' '+f.food.get_unit_display()+'. (X'+str(i)+')')
            if aux not in food:
                food.append(aux)
            else:
                index=food.index(aux)
                i+=1
                food[index]=str(f.food.name+' - '+str(f.food.consumer_amount)+' '+f.food.get_unit_display()+'.')+' (X'+str(i)+')'
        medicament_wormer=Medicament.objects.filter(farm=farm, is_wormer=True)
        application_medicament_wormer=ApplicationMedicament.objects.filter(medicament=medicament_wormer, cattle=cattle).order_by('medicament')
        wormer=[]
        i=1
        for w in application_medicament_wormer:
            aux=str(w.medicament.name+' - '+str(w.medicament.amount_application)+' '+w.medicament.get_unit_display()+'. (X'+str(i)+')')
            if aux not in wormer:
                wormer.append(aux)
            else:
                index=wormer.index(aux)
                i+=1
                wormer[index]=str(w.medicament.name+' - '+str(w.medicament.amount_application)+' '+w.medicament.get_unit_display()+'.')+' (X'+str(i)+')'


    # ... and do the preprocessing.
    table=[]
    # date, name, website, email, description, farm, adress, table
    rmlText = template.get(
            table,
            datetime.datetime.now().strftime("%Y-%m-%d"),
            'Reporte Individual de Ganado',
            'www.hatosganaderos.com',
            '*****@*****.**',
            'HatosGanaderos te ayuda con el control y organización de reproducción, alimentación, sanidad y producción de toda tu entidad ganadera.',
            'Ganadería Lojana',
            'Ciudadela universitaria',
            nombre,
            rp,
            raza,
            nacimiento,
            concepcion,
            edad,
            cattle_mother,
            cattle_father,
            celos,
            total_births,
            total_problems_births,
            count_milk,
            food,
            wormer,
            vaccine)

    # Finally generate the *.pdf output ...
    pdf = rml2pdf.parseString(rmlText)

    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(pdf, content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="somefilename.pdf"'

    return response