Example #1
0
def pdfgen(request):
	name = 'Jesus'
	last_name = 'Solis'

	path_rml = 'rml/hello.rml'
	t = Template(open(path_rml,'r').read())
	c = Context(
		{"name":name,"last_name":last_name}
	)
	rml = t.render(c)
	rml.encode('utf8')

	#print(rml)

	buf = BytesIO()
	rml2pdf.go(rml,outputFileName=buf)
	pdfData = buf.getvalue()
	buf.close()

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

	
	# p = canvas.Canvas(buffer)
	# p.drawString(250, 250, "Hello world.")
	# p.showPage()
	# p.save()
	# pdf = buffer.getvalue()
	# buffer.close()
	# response.write(pdf)
	
	return response
Example #2
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)
Example #3
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)
Example #4
0
 def testRml(self):
     source = open(self.fileName, 'rb').read()
     expectError = getattr(self,'expectError',False)
     try:
         rml2pdf.go(source)
         if expectError:
             raise ValueError('Expected error in %s did not occur' % self.fileName)
     except Exception as e:
         if not expectError:
             annotateException('while rendering %s' % self.fileName)
Example #5
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()
Example #7
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()
Example #8
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()
Example #9
0
def getPDF(request):
    """Returns PDF as a binary stream."""

    if 'q' in request.GET:

        rml = getRML(request.GET['q'])

        buf = cStringIO.StringIO()

        #create the pdf
        rml2pdf.go(rml, outputFileName=buf)
        buf.reset()
        pdfData = buf.read()

        #send the response
        response = HttpResponse(content_type='application/pdf')
        response.write(pdfData)
        response['Content-Disposition'] = 'attachment; filename=output.pdf'
        return response
Example #10
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()
Example #11
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()
Example #12
0
def getPDF(request):
    """Returns PDF as a binary stream."""

    pdfmetrics.registerFont(ttfonts.TTFont("song", "simsun.ttc"))

    if 'q' in request.GET:

        rml = getRML(request.GET['q'])

        buf = cStringIO.StringIO()

        #create the pdf
        rml2pdf.go(rml, outputFileName=buf)
        buf.reset()
        pdfData = buf.read()

        #send the response
        response = HttpResponse(mimetype='application/pdf')
        response.write(pdfData)
        response['Content-Disposition'] = 'attachment; filename=output.pdf'
        return response
Example #13
0
	def pdfcreator(self, request):
		req_unique_href = request.data.get('unique_href')
		try:
			order = Order.objects.get(unique_href = req_unique_href)
		except Order.DoesNotExist:
			return Response({"error": "Order not exists"})

		serializer = OrderInfoSerializer(order)
		if serializer:
			#import pdb
			#pdb.set_trace()
			lang =get_language_from_request(request)
			if lang == 'uk':
				t = get_template('templated_pdf/order_uk.rml')
			elif lang == 'ru':
				t = get_template('templated_pdf/order_ru.rml')
			else:
				t = get_template('templated_pdf/order.rml')

			c = Context({
				"id" : serializer.data['id'],
				"date": serializer.data['order_date'],
				"date_in": serializer.data['date_in'],
				"date_out": serializer.data['date_out'],
				"phone_number": serializer.data['person_phonenumber'],
				"first_name": serializer.data['person_firstname'],
				"middle_name": serializer.data['person_middlename'],
				"last_name": serializer.data['person_lastname'],
				"address": serializer.data['room_address'],
				"payment": serializer.data['payment'],
				"room_name": serializer.data['room_name'],
				"amount": serializer.data['amount'],
				})
			rml = t.render(c)
			rml_unicode = rml.encode('utf-8')
			#import pdb
			#pdb.set_trace()
			buf = BytesIO()
			a = rml2pdf.go(rml_unicode, outputFileName = buf)
			pdfData = buf.getvalue()
			response = HttpResponse(content_type='application/pdf')
			response.write(pdfData)
			response['Content-Disposition'] = 'attachment; filename="order.pdf"'
			return response
Example #14
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)

    #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)
#!/usr/bin/env python

# objective: read an RML file and output as a PDF

import datetime

from jinja2 import Environment, FileSystemLoader
from rlextra.rml2pdf import rml2pdf


jinja_env = Environment(loader=FileSystemLoader('./'))

date_today = datetime.date.today()
report_date = date_today.isoformat()

data = { 'report_author': 'Colin Johnson', 'report_date': report_date }

jinja_template = jinja_env.get_template('template.j2')
rml_template = jinja_template.render(**data)
rml_template = rml_template.encode('utf16')
rml2pdf.go(rml_template, './basic_report_using_rml.pdf')
#!/usr/bin/env python

# objective: read an RML file and output as a PDF

from rlextra.rml2pdf import rml2pdf


with open ('template.rml', 'r') as rml_file:
    rml_string=rml_file.read()

rml2pdf.go(rml_string, './basic_report_using_rml.pdf')
Example #17
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)