def _include_header(self) -> None:
     ptext = '<font size=18>Hashtag Report</font>'
     self.report_data.append(Paragraph(ptext, self.styles["Center"]))
     self.report_data.append(Spacer(1, 24))
	def create_pdf(self):
		"""
		Create a pdf
		"""
		story = []

		doc = SimpleDocTemplate(self.refile, pagesize=A4)
		styles = getSampleStyleSheet()

		spacer = Spacer(0, 0.07 * inch)

		story.append(spacer)
		story.append(spacer)

		ptext = '<font size=10><a>Customer Name: {}</a></font>'.format(self.custo.name)
		story.append(Paragraph(ptext, styles["Normal"]))
		story.append(spacer)

		ptext = '<font size=10><a>Customer Mobile Number: {}</a></font>'.format(
			self.custo.mobile_number)
		story.append(Paragraph(ptext, styles["Normal"]))
		story.append(spacer)

		line = MCLine(-30, 470)
		story.append(line)
		story.append(spacer)

		text_data = ["#", "Maint. Code", "Maint. Product", "Created Date", "Status", "Cost"]
		d = []
		font_size = 8
		centered = ParagraphStyle(name="centered", alignment=TA_CENTER)
		for text in text_data:
			ptext = "<font size=%s><b>%s</b></font>" % (font_size, text)
			p = Paragraph(ptext, centered)
			d.append(p)

		data = [d]

		line_num = 1

		formatted_line_data = []

		for val in self.custo.maintenance:
			if val.start_date != None \
					and val.cost_of_bill_of_material != None \
					and val.cost_of_labor != None:
				cost = val.cost_of_bill_of_material + val.cost_of_labor
				line_data = [str(line_num), val.m_code, val.product_of_maintenance,
							 val.created_at, getMaintenanceStatus(val)
					, cost]

				for item in line_data:
					ptext = "<font size=%s>%s</font>" % (font_size - 1, item)
					p = Paragraph(ptext, centered)
					formatted_line_data.append(p)
				data.append(formatted_line_data)
				formatted_line_data = []
				line_num += 1

		table = Table(data, colWidths=[20, 80, 180, 85, 90, 70], rowHeights=20
					  , style=[('GRID', (0, 0), (-1, -1), 0.5, colors.black)])
		story.append(table)
		story.append(spacer)
		#########################################################################################
		simplelistUP = []
		simplelistFN = []
		# mainlist = select_All_maintenance_customer(self.custo.id)
		for mainte in self.custo.maintenance:
			if mainte.start_date != None and mainte.done_date == None \
					and mainte.cost_of_bill_of_material != None \
					and mainte.cost_of_labor != None:
				simplelistUP.append(mainte.cost_of_bill_of_material + mainte.cost_of_labor)
			if mainte.done_date != None and mainte.close_at != None \
					and mainte.cost_of_bill_of_material != None \
					and mainte.cost_of_labor != None:
				simplelistFN.append(mainte.cost_of_bill_of_material + mainte.cost_of_labor)

		bomtxt = '<font size=9><p><b>Maintenance Under Processing Cost</b></p></font>'
		pbomtxt = Paragraph(bomtxt, styles["Normal"])

		bomtxtnum = "<p>{}<p>".format(sum(simplelistUP))
		pbomtxtnum = Paragraph(bomtxtnum, styles["Normal"])

		labtxt = '<font size=9><p><b>Maintenance Finished</b></p></font>'
		plabtxt = Paragraph(labtxt, styles["Normal"])

		labtxtnum = '<p>{}</p>'.format(sum(simplelistFN))
		plabtxtnum = Paragraph(labtxtnum, styles["Normal"])

		totxt = '<font size=9><p><b>Total</b></p></font>'
		ptotxt = Paragraph(totxt, styles["Normal"])

		totxtnum = '<p>{}</p>'.format(sum(simplelistFN) + sum(simplelistUP))
		ptotxtnum = Paragraph(totxtnum, styles["Normal"])
		data = [['', '', '', pbomtxt, pbomtxtnum],
				['', '', '', plabtxt, plabtxtnum],
				['', '', '', ptotxt, ptotxtnum]]
		t = Table(data, colWidths=[5, 5, 250, 170, 60], rowHeights=15)
		t.setStyle(TableStyle([('LINEABOVE', (3, 2), (-1, -1), 0.25, colors.black)]))
		story.append(t)
		for x in range(10):
			story.append(spacer)
		#
		# #########################################################################################
		actxt = '<font size=11><p><u>Accountant</u><br/>Rani Mohamed</p></font>'
		pactxt = Paragraph(actxt, centered)

		matxtnum = '<font size=11><p><u>Manager</u><br/>Mohamed Althubiti</p></font>'
		pmatxtnum = Paragraph(matxtnum, centered)
		data = [[pactxt, '', '', '', pmatxtnum]]
		t = Table(data, colWidths=[150, 5, 250, 5, 150])
		t.setStyle(TableStyle([('LINEABOVE', (3, 2), (-1, -1), 0.25, colors.black)]))
		story.append(t)
		#########################################################################################

		story.append(spacer)

		doc.build(story, onFirstPage=self.createDocument, onLaterPages=self.createDocument)

		subprocess.Popen([self.refile], shell=True)
Beispiel #3
0
def generatePdf():
    import time
    from reportlab.lib.enums import TA_JUSTIFY
    from reportlab.lib.pagesizes import letter
    from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image
    from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
    from reportlab.lib.units import inch

    doc = SimpleDocTemplate("report/static/Relatorio.pdf",
                            pagesize=letter,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=72,
                            bottomMargin=18)
    Story = []
    logo = "report/static/currentGraphic.png"
    logo2 = "report/static/voltageGraphic.png"
    logo3 = "report/static/activePowerGraphic.png"
    logo4 = "report/static/reactivePowerGraphic.png"
    logo5 = "report/static/apparentPowerGraphic.png"

    magName = "Pythonista"
    issueNum = 12
    subPrice = "99.00"
    limitedDate = "03/05/2010"
    freeGift = "tin foil hat"

    formatted_time = time.ctime()
    full_name = "SME-UnB"
    address_parts = ["Campus Universitario UnB", "Brasilia-DF, 70910-900"]

    im = Image(logo, 8 * inch, 5 * inch)
    im2 = Image(logo2, 8 * inch, 5 * inch)
    im3 = Image(logo3, 8 * inch, 5 * inch)
    im4 = Image(logo4, 8 * inch, 5 * inch)
    im5 = Image(logo5, 8 * inch, 5 * inch)

    Story.append(im)
    Story.append(im2)
    Story.append(im3)
    Story.append(im4)
    Story.append(im5)

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
    ptext = '<font size=12>%s</font>' % formatted_time

    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 12))

    ptext = '<font size=12>%s</font>' % full_name
    Story.append(Paragraph(ptext, styles["Normal"]))
    for part in address_parts:
        ptext = '<font size=12>%s</font>' % part.strip()
        Story.append(Paragraph(ptext, styles["Normal"]))

    Story.append(Spacer(1, 12))
    Story.append(Spacer(1, 12))
    ptext = '<font size=12>{ % trans Report Energy Monitoring % }</font>'
    Story.append(Paragraph(ptext, styles["Normal"]))

    doc.build(Story)
Beispiel #4
0
    def report(self, context, title):
        # set some characteristics for pdf document
        doc = SimpleDocTemplate(
            self.buffer,
            rightMargin=10,
            leftMargin=10,
            topMargin=20,
            bottomMargin=20,
            pagesize=self.pageSize,
        )

        # a collection of styles offer by the library
        styles = getSampleStyleSheet()

        # add custom paragraph style
        styles.add(
            ParagraphStyle(
                name="Title_Roboto",
                fontName='RobotoBold',
                fontSize=20,
                alignment=TA_CENTER,
            ))
        styles.add(
            ParagraphStyle(name="MainInfo", fontName='RobotoBold',
                           fontSize=12))
        styles.add(
            ParagraphStyle(
                name="TableHeader",
                fontName='RobotoBold',
                fontSize=11,
                alignment=TA_CENTER,
            ))
        styles.add(
            ParagraphStyle(name="MyNormal",
                           fontName='RobotoCondensed-Regular',
                           fontSize=10,
                           leading=12))
        styles.add(
            ParagraphStyle(
                name="MyNormalDecimal",
                fontName='RobotoCondensed-Regular',
                fontSize=10,
                aligment=TA_RIGHT,
            ))
        styles.add(
            ParagraphStyle(name="Categories",
                           fontName='RobotoCondensed-BoldItalic',
                           fontSize=11,
                           leading=12))

        # list used for elements added into document
        data = []
        data.append(Paragraph(title, styles['Title_Roboto']))
        # insert a blank space
        data.append(Spacer(1, 24))

        (data.append(
            Paragraph(
                _('Description') + ': ' + context['trip'].description,
                styles['MainInfo']))) if context['trip'].description else ''
        data.append(Spacer(1, 4))
        data.append(
            Paragraph(
                _('Created by') + ': ' + str(context['trip'].created_by),
                styles['MainInfo']))
        data.append(Spacer(1, 4))
        data.append(
            Paragraph(
                _('Total Cost') + ': ' + str(context['trip'].price),
                styles['MainInfo']))
        data.append(Spacer(1, 12))

        table_data = []
        # table header
        table_data.append([
            Paragraph(_('Category/ No.'), styles['TableHeader']),
            Paragraph(_('Name'), styles['TableHeader']),
            Paragraph(_('Start time'), styles['TableHeader']),
            Paragraph(_('End time'), styles['TableHeader']),
            Paragraph(_('Start point'), styles['TableHeader']),
            Paragraph(_('End point'), styles['TableHeader']),
            Paragraph(_('Means of transport'), styles['TableHeader']),
            Paragraph(_('Address'), styles['TableHeader']),
            Paragraph(_('Cost'), styles['TableHeader'])
        ])
        table_data.append([
            Paragraph(_('Journeys'), styles['Categories']), '', '', '', '', '',
            '', ''
        ])
        for i, journey in enumerate(context['trip'].journey_set.all()):
            if isinstance(journey.start_time, datetime):
                start_time = (journey.start_time).strftime('%d.%m.%Y (%H:%M)')
            else:
                start_time = ''
            if isinstance(journey.end_time, datetime):
                end_time = (journey.end_time).strftime('%d.%m.%Y (%H:%M)')
            else:
                end_time = ''
            table_data.append([
                Paragraph(str(i + 1), styles['MyNormal']),
                '',
                Paragraph(formatTableCellData(start_time), styles['MyNormal']),
                Paragraph(formatTableCellData(end_time), styles['MyNormal']),
                Paragraph(formatTableCellData(journey.start_point),
                          styles['MyNormal']),
                Paragraph(formatTableCellData(journey.end_point),
                          styles['MyNormal']),
                Paragraph(formatTableCellData(journey.means_of_transport),
                          styles['MyNormal']),
                '',
                Paragraph(formatTableCellData(journey.price),
                          styles['MyNormalDecimal']),
            ])
        table_data.append([
            Paragraph(_('Accommodations'), styles['Categories']), '', '', '',
            '', '', '', ''
        ])
        for i, accommodation in enumerate(
                context['trip'].accommodation_set.all()):
            if isinstance(accommodation.start_time, datetime):
                start_time = (
                    accommodation.start_time).strftime('%d.%m.%Y (%H:%M)')
            else:
                start_time = ''
            if isinstance(accommodation.end_time, datetime):
                end_time = (
                    accommodation.end_time).strftime('%d.%m.%Y (%H:%M)')
            else:
                end_time = ''

            table_data.append([
                Paragraph(str(i + 1), styles['MyNormal']),
                Paragraph(formatTableCellData(accommodation.name),
                          styles['MyNormal']),
                Paragraph(formatTableCellData(start_time), styles['MyNormal']),
                Paragraph(formatTableCellData(end_time), styles['MyNormal']),
                '',
                '',
                '',
                Paragraph(formatTableCellData(accommodation.address),
                          styles['MyNormal']),
                Paragraph(formatTableCellData(accommodation.price),
                          styles['MyNormalDecimal']),
            ])
        table_data.append([
            Paragraph(_('Attractions'), styles['Categories']), '', '', '', '',
            '', '', ''
        ])
        for i, attraction in enumerate(context['trip'].attraction_set.all()):
            if isinstance(attraction.start_time, datetime):
                start_time = (
                    attraction.start_time).strftime('%d.%m.%Y (%H:%M)')
            else:
                start_time = ''
            table_data.append([
                Paragraph(str(i + 1), styles['MyNormal']),
                Paragraph(formatTableCellData(attraction.name),
                          styles['MyNormal']),
                Paragraph(formatTableCellData(start_time), styles['MyNormal']),
                '',
                '',
                '',
                '',
                Paragraph(formatTableCellData(attraction.address),
                          styles['MyNormal']),
                Paragraph(formatTableCellData(attraction.price),
                          styles['MyNormalDecimal']),
            ])
        # create table
        trip_details_table = Table(table_data, colWidths=[doc.width / 9.0] * 9)
        trip_details_table.setStyle(
            TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                        ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
                        ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                        ('BACKGROUND', (0, 0), (-1, 0), colors.gray)]))
        data.append(trip_details_table)
        data.append(Spacer(1, 12))

        # data.append(Paragraph((_('More info')), styles['MainInfo']))
        data.append(Spacer(1, 4))
        data.append(Paragraph((_('Journeys') + ':'), styles['Categories']))
        for i, journey in enumerate(context['trip'].journey_set.all()):
            if formatTableCellData(journey.more_info) != '':
                data.append(
                    Paragraph((str(i + 1) + '. ' +
                               formatTableCellData(journey.more_info)),
                              styles['MyNormal']))

        data.append(
            Paragraph((_('Accommodations') + ':'), styles['Categories']))
        for i, accommodation in enumerate(
                context['trip'].accommodation_set.all()):
            if formatTableCellData(accommodation.more_info) != '':
                data.append(
                    Paragraph((str(i + 1) + '. ' +
                               formatTableCellData(accommodation.more_info)),
                              styles['MyNormal']))

        data.append(Paragraph((_('Attractions') + ':'), styles['Categories']))
        for i, attraction in enumerate(context['trip'].attraction_set.all()):
            if formatTableCellData(attraction.more_info) != '':
                data.append(
                    Paragraph((str(i + 1) + '. ' +
                               formatTableCellData(attraction.more_info)),
                              styles['MyNormal']))

        # create document
        doc.build(data)
        pdf = self.buffer.getvalue()
        self.buffer.close()
        return pdf
Beispiel #5
0
def fullTest(fileName="test_full.pdf"):
    """Creates large-ish test document with a variety of parameters"""

    story = []

    styles = getSampleStyleSheet()
    styleN = styles['Normal']
    styleH = styles['Heading1']
    styleH2 = styles['Heading2']
    story = []

    story.append(
        Paragraph('ReportLab Barcode Test Suite - full output', styleH))
    story.append(Paragraph('Generated on %s' % time.ctime(time.time()),
                           styleN))

    story.append(Paragraph('', styleN))
    story.append(Paragraph('Repository information for this build:', styleN))
    #see if we can figure out where it was built, if we're running in source
    if os.path.split(os.getcwd())[-1] == 'barcode' and os.path.isdir('.svn'):
        #runnning in a filesystem svn copy
        infoLines = os.popen('svn info').read()
        story.append(Preformatted(infoLines, styles["Code"]))

    story.append(Paragraph('About this document', styleH2))
    story.append(Paragraph('History and Status', styleH2))

    story.append(
        Paragraph(
            """
        This is the test suite and docoumentation for the ReportLab open source barcode API,
        being re-released as part of the forthcoming ReportLab 2.0 release.
        """, styleN))

    story.append(
        Paragraph(
            """
        Several years ago Ty Sarna contributed a barcode module to the ReportLab community.
        Several of the codes were used by him in hiw work and to the best of our knowledge
        this was correct.  These were written as flowable objects and were available in PDFs,
        but not in our graphics framework.  However, we had no knowledge of barcodes ourselves
        and did not advertise or extend the package.
        """, styleN))

    story.append(
        Paragraph(
            """
        We "wrapped" the barcodes to be usable within our graphics framework; they are now available
        as Drawing objects which can be rendered to EPS files or bitmaps.  For the last 2 years this
        has been available in our Diagra and Report Markup Language products.  However, we did not
        charge separately and use was on an "as is" basis.
        """, styleN))

    story.append(
        Paragraph(
            """
        A major licensee of our technology has kindly agreed to part-fund proper productisation
        of this code on an open source basis in Q1 2006.  This has involved addition of EAN codes
        as well as a proper testing program.  Henceforth we intend to publicise the code more widely,
        gather feedback, accept contributions of code and treat it as "supported".  
        """, styleN))

    story.append(
        Paragraph(
            """
        This involved making available both downloads and testing resources.  This PDF document
        is the output of the current test suite.  It contains codes you can scan (if you use a nice sharp
        laser printer!), and will be extended over coming weeks to include usage examples and notes on
        each barcode and how widely tested they are.  This is being done through documentation strings in
        the barcode objects themselves so should always be up to date.
        """, styleN))

    story.append(Paragraph('Usage examples', styleH2))
    story.append(Paragraph("""
        To be completed
        """, styleN))

    story.append(Paragraph('The codes', styleH2))
    story.append(
        Paragraph(
            """
        Below we show a scannable code from each barcode, with and without human-readable text.
        These are magnified about 2x from the natural size done by the original author to aid
        inspection.  This will be expanded to include several test cases per code, and to add
        explanations of checksums.  Be aware that (a) if you enter numeric codes which are too
        short they may be prefixed for you (e.g. "123" for an 8-digit code becomes "00000123"),
        and that the scanned results and readable text will generally include extra checksums
        at the end.
        """, styleN))

    codeNames = getCodeNames()
    from reportlab.lib.utils import flatten
    width = [float(x[8:]) for x in sys.argv if x.startswith('--width=')]
    height = [float(x[9:]) for x in sys.argv if x.startswith('--height=')]
    isoScale = [int(x[11:]) for x in sys.argv if x.startswith('--isoscale=')]
    options = {}
    if width: options['width'] = width[0]
    if height: options['height'] = height[0]
    if isoScale: options['isoScale'] = isoScale[0]
    scales = [x[8:].split(',') for x in sys.argv if x.startswith('--scale=')]
    scales = list(map(float, scales and flatten(scales) or [1]))
    scales = list(map(float, scales and flatten(scales) or [1]))
    for scale in scales:
        story.append(PageBreak())
        story.append(Paragraph('Scale = %.1f' % scale, styleH2))
        story.append(Spacer(36, 12))
        for codeName in codeNames:
            s = [Paragraph('Code: ' + codeName, styleH2)]
            for hr in (0, 1):
                s.append(Spacer(36, 12))
                dr = createBarcodeDrawing(codeName,
                                          humanReadable=hr,
                                          **options)
                dr.renderScale = scale
                s.append(dr)
                s.append(Spacer(36, 12))
            s.append(Paragraph('Barcode should say: ' + dr._bc.value, styleN))
            story.append(KeepTogether(s))

    SimpleDocTemplate(fileName).build(story)
    print('created', fileName)
    def create_pdf(self):
        """
		Create a pdf
		"""
        story = []

        doc = SimpleDocTemplate(self.refile, pagesize=A4)
        styles = getSampleStyleSheet()

        spacer = Spacer(0, 0.07 * inch)

        story.append(spacer)
        story.append(spacer)

        line = MCLine(-30, 470)
        story.append(line)
        story.append(spacer)

        text_data = ["#", "RM. Code", "RM. Name", "RM. Size", "RM. INV. QTY."]
        d = []
        font_size = 8
        centered = ParagraphStyle(name="centered", alignment=TA_CENTER)
        for text in text_data:
            ptext = "<font size=%s><b>%s</b></font>" % (font_size, text)
            p = Paragraph(ptext, centered)
            d.append(p)

        data = [d]

        line_num = 1

        formatted_line_data = []

        for val in select_all_raw_material():

            line_data = [
                str(line_num), val.code, val.name, val.string_size, val.inv_qty
            ]

            for item in line_data:
                ptext = "<font size=%s>%s</font>" % (font_size - 1, item)
                p = Paragraph(ptext, centered)
                formatted_line_data.append(p)
            data.append(formatted_line_data)
            formatted_line_data = []
            line_num += 1

        table = Table(data,
                      colWidths=[50, 80, 180, 100, 70],
                      rowHeights=20,
                      style=[('GRID', (0, 0), (-1, -1), 0.5, colors.black)])
        story.append(table)
        story.append(spacer)

        matxtnum = '<font size=11><p><u>Manager</u><br/>Mohamed Althubiti</p></font>'
        pmatxtnum = Paragraph(matxtnum, centered)
        data = [['', '', '', '', pmatxtnum]]
        t = Table(data, colWidths=[150, 5, 250, 5, 150])
        t.setStyle(
            TableStyle([('LINEABOVE', (3, 2), (-1, -1), 0.25, colors.black)]))
        story.append(t)
        #########################################################################################

        story.append(spacer)

        doc.build(story,
                  onFirstPage=self.createDocument,
                  onLaterPages=self.createDocument)

        subprocess.Popen([self.refile], shell=True)
Beispiel #7
0
 def append_text(self, text, style, space):
     self.story_arr.append(Paragraph(text, style))
     self.story_arr.append(Spacer(1, space))
Beispiel #8
0
    def OnBoutonOk(self, event):
        dictOptions = self.ctrl_parametres.GetOptions()
        if dictOptions == False:
            return

        # Récupération des paramètres
        listeIDfactures = []
        montantTotal = 0.0
        for track in self.tracks:
            listeIDfactures.append(track.IDfacture)
            montantTotal += -track.solde

        if len(listeIDfactures) == 0: conditionFactures = "()"
        elif len(listeIDfactures) == 1:
            conditionFactures = "(%d)" % listeIDfactures[0]
        else:
            conditionFactures = str(tuple(listeIDfactures))

        DB = GestionDB.DB()
        req = """
        SELECT prestations.IDprestation, prestations.IDfacture, prestations.label, prestations.montant, 
        prestations.IDindividu, individus.nom, individus.prenom,
        prestations.IDactivite, activites.nom
        FROM prestations
        LEFT JOIN individus ON prestations.IDindividu = individus.IDindividu
        LEFT JOIN activites ON activites.IDactivite = prestations.IDactivite
        WHERE prestations.IDfacture IN %s
        GROUP BY prestations.IDprestation
        ORDER BY prestations.date
        ;""" % conditionFactures
        DB.ExecuterReq(req)
        listePrestations = DB.ResultatReq()

        # Récupération des prélèvements
        req = """SELECT
            prelevements.IDprelevement, prelevements.prelevement_iban,
            prelevements.IDfacture, lots_prelevements.date,
            prelevement_reference_mandat, titulaire
            FROM prelevements
            LEFT JOIN lots_prelevements ON lots_prelevements.IDlot = prelevements.IDlot
            WHERE prelevements.IDfacture IN %s
            ;""" % conditionFactures
        DB.ExecuterReq(req)
        listePrelevements = DB.ResultatReq()
        # Pièces PES ORMC
        req = """SELECT
            pes_pieces.IDpiece, pes_pieces.prelevement_iban, pes_pieces.IDfacture,
            pes_lots.date_prelevement, pes_pieces.prelevement_IDmandat, pes_pieces.prelevement_titulaire
            FROM pes_pieces
            LEFT JOIN pes_lots ON pes_lots.IDlot = pes_pieces.IDlot
            WHERE pes_pieces.prelevement_IDmandat IS NOT NULL AND pes_pieces.prelevement=1 AND pes_pieces.IDfacture IN %s
            ;""" % conditionFactures
        DB.ExecuterReq(req)
        listePieces = DB.ResultatReq()
        dictPrelevements = {}
        for listeDonneesPrel in (listePrelevements, listePieces):
            for IDprelevement, iban, IDfacture, datePrelevement, rum, titulaire in (
                    listeDonneesPrel):
                datePrelevement = UTILS_Dates.DateEngFr(datePrelevement)
                dictPrelevements[IDfacture] = {
                    "IDprelevement": IDprelevement,
                    "datePrelevement": datePrelevement,
                    "iban": iban,
                    "rum": rum,
                    "titulaire": titulaire
                }

        DB.Close()
        # Calcul totaux prélèvements
        nbrFactPrelev = len(dictPrelevements)
        montantTotalPrelev = 0.0
        for track in self.tracks:
            if dictPrelevements.has_key(track.IDfacture):
                montantTotalPrelev += -track.solde

        dictPrestations = {}
        dictIndividus = {}
        dictActivites = {}
        dictTotaux = {}
        for IDprestation, IDfacture, label, montant, IDindividu, nom, prenom, IDactivite, nomActivite in listePrestations:

            if dictActivites != None and dictActivites.has_key(
                    IDactivite) == False:
                dictActivites[IDactivite] = nomActivite

            if IDindividu != None and dictIndividus.has_key(
                    IDindividu) == False and prenom != None:
                dictIndividus[IDindividu] = u"%s %s" % (nom, prenom)

            if dictPrestations.has_key(IDfacture) == False:
                dictPrestations[IDfacture] = {}
            if dictPrestations[IDfacture].has_key(IDindividu) == False:
                dictPrestations[IDfacture][IDindividu] = {}
            if dictPrestations[IDfacture][IDindividu].has_key(label) == False:
                dictPrestations[IDfacture][IDindividu][label] = {
                    "quantite": 0,
                    "montant": 0.0,
                    "IDactivite": IDactivite
                }

            if dictTotaux.has_key(IDactivite) == False:
                dictTotaux[IDactivite] = {}
            if dictTotaux[IDactivite].has_key(label) == False:
                dictTotaux[IDactivite][label] = {"quantite": 0, "montant": 0.0}

            dictTotaux[IDactivite][label]["quantite"] += 1
            dictTotaux[IDactivite][label]["montant"] += montant

            dictPrestations[IDfacture][IDindividu][label]["quantite"] += 1
            dictPrestations[IDfacture][IDindividu][label]["montant"] += montant

        # Création du PDF
        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
        from reportlab.platypus.flowables import ParagraphAndImage, Image
        from reportlab.rl_config import defaultPageSize
        from reportlab.lib.units import inch, cm
        from reportlab.lib.utils import ImageReader
        from reportlab.lib import colors
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        self.hauteur_page = defaultPageSize[1]
        self.largeur_page = defaultPageSize[0]

        # Initialisation du PDF
        PAGE_WIDTH, PAGE_HEIGHT = defaultPageSize
        nomDoc = FonctionsPerso.GenerationNomDoc("RECAP_FACTURES", "pdf")
        if sys.platform.startswith("win"): nomDoc = nomDoc.replace("/", "\\")
        doc = SimpleDocTemplate(nomDoc, topMargin=30, bottomMargin=30)
        story = []

        largeurContenu = 520

        # Création du titre du document
        def Header():
            dataTableau = []
            largeursColonnes = ((420, 100))
            dateDuJour = UTILS_Dates.DateEngFr(str(datetime.date.today()))
            dataTableau.append(
                (dictOptions["titre_texte"], _(u"%s\nEdité le %s") %
                 (UTILS_Organisateur.GetNom(), dateDuJour)))
            style = TableStyle([
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                ('ALIGN', (0, 0), (0, 0),
                 ConvertAlignement1(dictOptions["titre_alignement"])),
                ('FONT', (0, 0), (0, 0), "Helvetica-Bold",
                 dictOptions["titre_taille_texte"]),
                ('ALIGN', (1, 0), (1, 0), 'RIGHT'),
                ('FONT', (1, 0), (1, 0), "Helvetica", 6),
            ])
            tableau = Table(dataTableau, largeursColonnes)
            tableau.setStyle(style)
            story.append(tableau)
            story.append(Spacer(0, 20))

        # Insère un header
        Header()

        couleurFond1 = ConvertCouleurWXpourPDF(dictOptions["couleur_fond_1"])
        couleurFond2 = ConvertCouleurWXpourPDF(dictOptions["couleur_fond_2"])

        styleIntroduction = ParagraphStyle(
            name="introduction",
            fontName="Helvetica",
            alignment=ConvertAlignement2(dictOptions["intro_alignement"]),
            fontSize=dictOptions["intro_taille_texte"],
            spaceAfter=0,
            leading=8,
            spaceBefore=0)
        styleConclusion = ParagraphStyle(
            name="conclusion",
            fontName="Helvetica",
            alignment=ConvertAlignement2(dictOptions["conclusion_alignement"]),
            fontSize=dictOptions["conclusion_taille_texte"],
            spaceAfter=0,
            leading=8,
            spaceBefore=0)

        styleLabel = ParagraphStyle(name="label",
                                    fontName="Helvetica",
                                    alignment=1,
                                    fontSize=5,
                                    spaceAfter=0,
                                    leading=8,
                                    spaceBefore=0)
        styleTexte = ParagraphStyle(name="label",
                                    fontName="Helvetica",
                                    alignment=0,
                                    fontSize=7,
                                    spaceAfter=0,
                                    leading=8,
                                    spaceBefore=0)
        styleTexte2 = ParagraphStyle(name="label",
                                     fontName="Helvetica",
                                     alignment=1,
                                     fontSize=7,
                                     spaceAfter=0,
                                     leading=8,
                                     spaceBefore=0)
        styleMontant = ParagraphStyle(name="label",
                                      fontName="Helvetica",
                                      alignment=2,
                                      fontSize=7,
                                      spaceAfter=0,
                                      leading=8,
                                      spaceBefore=0)

        # Intro
        story.append(Paragraph(dictOptions["intro_texte"], styleIntroduction))
        story.append(Spacer(0, 20))

        # Factures
        if dictOptions["type_document"] in (0, 1):

            for track in self.tracks:

                numero = track.numero
                if track.etat == "annulation":
                    numero = u"%s (Annulée)" % numero

                solde = track.solde
                if solde != 0.0:
                    solde = -solde

                # Numéro de facture
                dataTableau = []
                largeursColonnes = [100, 100, largeurContenu - 100 - 100]
                dataTableau.append((
                    _(u"Facture n°%s") % numero,
                    u"%.2f %s" % (solde, SYMBOLE),
                    _(u"Edité le %s | Echéance le %s | Période du %s au %s")
                    % (UTILS_Dates.DateDDEnFr(track.date_edition),
                       UTILS_Dates.DateDDEnFr(track.date_echeance),
                       UTILS_Dates.DateDDEnFr(track.date_debut),
                       UTILS_Dates.DateDDEnFr(track.date_fin)),
                ))
                tableau = Table(dataTableau, largeursColonnes)
                listeStyles = [
                    ('FONT', (0, 0), (1, -1), "Helvetica-Bold", 7),
                    ('FONT', (2, -1), (2, -1), "Helvetica", 6),
                    ('BACKGROUND', (0, 0), (-1, -1), couleurFond1),
                    ('ALIGN', (2, -1), (2, -1), 'RIGHT'),
                    ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ]
                tableau.setStyle(TableStyle(listeStyles))
                story.append(tableau)

                # Famille
                if track.prelevement == True:
                    if dictPrelevements.has_key(track.IDfacture):
                        textePrelevement = _(
                            u"IBAN : %s | RUM : %s | Titulaire : %s | Le : %s "
                        ) % (dictPrelevements[track.IDfacture]["iban"],
                             dictPrelevements[track.IDfacture]["rum"],
                             dictPrelevements[track.IDfacture]["titulaire"],
                             dictPrelevements[
                                 track.IDfacture]["datePrelevement"])
                    else:
                        textePrelevement = _(
                            u"N° Compte : %s | Etab : %s | Guichet : %s | Clé : %s | Titulaire : %s"
                        ) % (track.prelevement_numero, track.prelevement_etab,
                             track.prelevement_guichet, track.prelevement_cle,
                             track.prelevement_payeur)
                else:
                    textePrelevement = u""

                if track.adresse_famille["rue"] != None:
                    rue = track.adresse_famille["rue"]
                else:
                    rue = u""
                if track.adresse_famille["cp"] != None:
                    cp = track.adresse_famille["cp"]
                else:
                    cp = u""
                if track.adresse_famille["ville"] != None:
                    ville = track.adresse_famille["ville"]
                else:
                    ville = u""

                dataTableau = [
                    (Paragraph(_(u"Famille"),
                               styleLabel), Paragraph(_(u"Adresse"),
                                                      styleLabel),
                     Paragraph(_(u"Prélèvement bancaire"), styleLabel)),
                ]
                largeursColonnes = [180, 140, largeurContenu - 320]
                dataTableau.append((
                    Paragraph(track.nomsTitulaires, styleTexte),
                    (Paragraph(rue, styleTexte),
                     Paragraph(u"%s %s" % (cp, ville), styleTexte)),
                    Paragraph(textePrelevement, styleTexte),
                ))
                tableau = Table(dataTableau, largeursColonnes)
                listeStyles = [
                    ('TOPPADDING', (0, 0), (-1, 0), 0),
                    ('BOTTOMPADDING', (0, 0), (-1, 0), -1),
                    ('FONT', (0, -1), (-1, -1), "Helvetica", 7),
                    ('GRID', (0, 0), (-1, 0), 0.25, colors.black),
                    ('BOX', (0, 1), (-1, 1), 0.25, colors.black),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('BACKGROUND', (0, 0), (-1, 0), couleurFond2),
                ]
                tableau.setStyle(TableStyle(listeStyles))
                story.append(tableau)

                # Détail des prestations
                if dictOptions[
                        "type_document"] == 0 and dictPrestations.has_key(
                            track.IDfacture):

                    dataTableau = [
                        (Paragraph(_(u"Individu"), styleLabel),
                         Paragraph(_(u"Activité"), styleLabel),
                         Paragraph(_(u"Prestation"), styleLabel),
                         Paragraph(_(u"Quantité"), styleLabel),
                         Paragraph(_(u"Montant total"), styleLabel)),
                    ]
                    largeursColonnes = [130, 120, 185, 35, 50]

                    for IDindividu, dictLabels in dictPrestations[
                            track.IDfacture].iteritems():

                        if dictIndividus.has_key(IDindividu):
                            labelIndividu = dictIndividus[IDindividu]
                        else:
                            labelIndividu = u""

                        listeActivites = []
                        listeLabels = []
                        listeQuantites = []
                        listeMontants = []
                        for labelPrestation, dictTemp in dictLabels.iteritems(
                        ):

                            if dictTemp[
                                    "IDactivite"] != None and dictActivites.has_key(
                                        dictTemp["IDactivite"]):
                                labelActivite = dictActivites[
                                    dictTemp["IDactivite"]]
                            else:
                                labelActivite = u""

                            listeActivites.append(
                                Paragraph(labelActivite[:35], styleTexte2))
                            listeLabels.append(
                                Paragraph(labelPrestation[:40], styleTexte2))
                            listeQuantites.append(
                                Paragraph(str(dictTemp["quantite"]),
                                          styleTexte2))
                            listeMontants.append(
                                Paragraph(
                                    u"%.2f %s" %
                                    (dictTemp["montant"], SYMBOLE),
                                    styleMontant))

                        dataTableau.append((
                            Paragraph(labelIndividu, styleTexte2),
                            listeActivites,
                            listeLabels,
                            listeQuantites,
                            listeMontants,
                        ))

                    tableau = Table(dataTableau, largeursColonnes)
                    listeStyles = [
                        ('TOPPADDING', (0, 0), (-1, 0), 0),
                        ('BOTTOMPADDING', (0, 0), (-1, 0), -1),
                        ('FONT', (0, -1), (-1, -1), "Helvetica", 7),
                        ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
                        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                        ('BACKGROUND', (0, 0), (-1, 0), couleurFond2),
                    ]
                    tableau.setStyle(TableStyle(listeStyles))
                    story.append(tableau)

                story.append(Spacer(0, 10))

        # Totaux
        dataTableau = [
            (_(u"Totaux par activités et prestations"), "", "", ""),
            (Paragraph(_(u"Activités"),
                       styleLabel), Paragraph(_(u"Prestations"), styleLabel),
             Paragraph(_(u"Quantité"),
                       styleLabel), Paragraph(_(u"Montant"), styleLabel)),
        ]
        largeursColonnes = [195, 240, 35, 50]

        for IDactivite, dictLabels in dictTotaux.iteritems():

            if IDactivite == None:
                nomActivite = _(u"Prestations familiales")
            else:
                nomActivite = dictActivites[IDactivite]

            listeLabels = []
            listeQuantites = []
            listeMontants = []
            quantiteActivite = 0
            totalActivite = 0.0
            for label, dictTemp in dictLabels.iteritems():
                listeLabels.append(Paragraph(label, styleTexte2))
                listeQuantites.append(
                    Paragraph(str(dictTemp["quantite"]), styleTexte2))
                listeMontants.append(
                    Paragraph(u"%.2f %s" % (dictTemp["montant"], SYMBOLE),
                              styleMontant))
                quantiteActivite += dictTemp["quantite"]
                totalActivite += dictTemp["montant"]

            listeLabels.append(
                Paragraph(_(u"<b><i>Total de l'activité</i></b>"),
                          styleTexte2))
            listeQuantites.append(
                Paragraph("<b><i>%d</i></b>" % quantiteActivite, styleTexte2))
            listeMontants.append(
                Paragraph(u"<b><i>%.2f %s</i></b>" % (totalActivite, SYMBOLE),
                          styleMontant))

            dataTableau.append((
                Paragraph(nomActivite, styleTexte2),
                listeLabels,
                listeQuantites,
                listeMontants,
            ))

        tableau = Table(dataTableau, largeursColonnes)
        listeStyles = [
            ('TOPPADDING', (0, 1), (-1, 1), 0),
            ('BOTTOMPADDING', (0, 1), (-1, 1), -1),
            ('FONT', (1, -1), (-1, -1), "Helvetica", 7),
            ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 7),
            ('BOX', (0, 0), (-1, 0), 0.25, colors.black),
            ('GRID', (0, 1), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('BACKGROUND', (0, 0), (-1, 0), couleurFond1),
            ('BACKGROUND', (0, 1), (-1, 1), couleurFond2),
        ]
        tableau.setStyle(TableStyle(listeStyles))
        story.append(tableau)

        story.append(Spacer(0, 10))

        # Texte de conclusion
        conclusion_texte = dictOptions["conclusion_texte"]
        conclusion_texte = conclusion_texte.replace("{NBRE_FACTURES}",
                                                    str(len(self.tracks)))
        conclusion_texte = conclusion_texte.replace(
            "{TOTAL_FACTURES}", u"%.2f %s" % (montantTotal, SYMBOLE))
        conclusion_texte = conclusion_texte.replace("{NBRE_FACT_PRELEV}",
                                                    str(nbrFactPrelev))
        conclusion_texte = conclusion_texte.replace(
            "{TOTAL_FACT_PRELEV}", u"%.2f %s" % (montantTotalPrelev, SYMBOLE))
        story.append(Paragraph(conclusion_texte, styleConclusion))

        # Enregistrement et ouverture du PDF
        try:
            doc.build(story)
        except Exception, err:
            print "Erreur dans ouverture PDF :", err
            if "Permission denied" in err:
                dlg = wx.MessageDialog(
                    None,
                    _(u"Noethys ne peut pas créer le PDF.\n\nVeuillez vérifier qu'un autre PDF n'est pas déjà ouvert en arrière-plan..."
                      ), _(u"Erreur d'édition"), wx.OK | wx.ICON_ERROR)
                dlg.ShowModal()
                dlg.Destroy()
                return False
Beispiel #9
0
    def make_pdf_content(self, response, feed):
        self.package_id = feed.package_id
        self.tlp = feed.tlp
        feed_pdf_stix = _get_feed_pdf_stix(feed)
        # style変更
        styles = getSampleStyleSheet()
        for name in ('Normal', 'BodyText', 'Title', 'Heading1', 'Heading2',
                     'Heading3', 'Heading4', 'Heading5', 'Heading6', 'Bullet',
                     'Definition', 'Code'):
            styles[name].wordWrap = 'CJK'
            styles[name].fontName = 'meiryo'

        # doc作成
        doc = SimpleDocTemplate(response, pagesize=portrait(A4))

        story = []

        # Title
        string = '<b>Title:</b> %s' % iocextract.defang(feed.title)
        story.append(Paragraph(string, styles['Normal']))

        # Author
        if feed.administrative_code is None:
            administrative_code = '-'
        else:
            administrative_code = feed.administrative_code
        if feed.country_code is None:
            country_code = '-'
        else:
            country_code = feed.country_code

        string = '%s (%s - %s, %s)' % (feed.user.get_screen_name(),
                                       feed.user.get_sector_display(),
                                       administrative_code, country_code)
        txt = '<b>Author:</b> %s' % (string)
        story.append(Paragraph(txt, styles['Normal']))

        # Produced Time
        ts = feed_pdf_stix.get_timestamp()
        txt = '<b>Produced Time:</b> %s' % (ts)
        story.append(Paragraph(txt, styles['Normal']))

        # STIX Package ID
        string = str(feed.package_id)
        txt = '<b>STIX Package ID:</b> %s' % (string)
        story.append(Paragraph(txt, styles['Normal']))

        # 空行
        story.append(Spacer(1, 1.0 * cm))

        # content
        txt = '<b>Content:</b>'
        story.append(Paragraph(txt, styles['Normal']))
        txt = iocextract.defang(feed.post)
        story.append(Paragraph(txt, styles['Normal']))

        # 空行
        story.append(Spacer(1, 1.0 * cm))

        # テーブルのセルスタイル設定
        style = ParagraphStyle(name='Normal',
                               fontName=self.FONT_MEIRYO,
                               fontSize=9,
                               leading=9)

        # indicators
        indicators = feed_pdf_stix.get_indicators()
        if len(indicators) == 0:
            txt = '<b>Indicators:</b> No Data'
            story.append(Paragraph(txt, styles['Normal']))
        else:
            txt = '<b>Indicators:</b>'
            story.append(Paragraph(txt, styles['Normal']))
            # 空行
            story.append(Spacer(1, 0.1 * cm))
            # Table
            d = [
                # header
                ['Type', 'Indicators'],
            ]

            # Sort(優先度は1列目、2列目の順で名前順)
            indicators.sort(key=lambda x: x[1])
            indicators.sort(key=lambda x: x[0])

            # STIXからObservablesとIndicatorsを抽出
            for item in indicators:
                (type_, value, _) = item
                item = []
                item.append(Paragraph(type_, style))
                # file_nameの場合は値がパイプで囲まれている
                if type_ == 'file_name':
                    # 前後のパイプをトリミング
                    value = value[1:-1]
                # defang
                value = iocextract.defang(value)
                item.append(Paragraph(value, style))
                d.append(item)

            # テーブル作成とスタイル設定
            indicators_table = self._create_table(d, len(indicators),
                                                  (20 * mm, 135 * mm))
            story.append(indicators_table)

        # 空行
        story.append(Spacer(1, 1.0 * cm))

        # Exploit Targets
        exploit_targets = feed_pdf_stix.get_exploit_targets()
        if len(exploit_targets) == 0:
            txt = '<b>Exploit Targets:</b> No Data'
            story.append(Paragraph(txt, styles['Normal']))
        else:
            txt = '<b>Exploit Targets:</b>'
            story.append(Paragraph(txt, styles['Normal']))
            # 空行
            story.append(Spacer(1, 0.1 * cm))
            # Table
            d = [
                # header
                ['CVE', 'Description'],
            ]

            # Description情報を抽出
            for item in exploit_targets:
                (_, cve, value) = item
                item = []
                value = self._html_text(value)
                item.append(Paragraph(cve, style))
                item.append(Paragraph(value, style))
                d.append(item)

            # テーブル作成とスタイル設定
            cve_table = self._create_table(d, len(exploit_targets),
                                           (30 * mm, 125 * mm))
            story.append(cve_table)

        # 空行
        story.append(Spacer(1, 1.0 * cm))

        # Threat Actors
        threat_actors = feed_pdf_stix.get_threat_actors()
        if len(threat_actors) == 0:
            txt = '<b>Threat Actors:</b> No Data'
            story.append(Paragraph(txt, styles['Normal']))
        else:
            txt = '<b>Threat Actors:</b>'
            story.append(Paragraph(txt, styles['Normal']))
            # 空行
            story.append(Spacer(1, 0.1 * cm))
            # Table
            d = [
                # header
                ['Name', 'Description'],
            ]

            # Description情報を抽出
            for item in threat_actors:
                (_, actor, value) = item
                item = []
                item.append(Paragraph(actor, style))
                item.append(Paragraph(str(value), style))
                d.append(item)

            # テーブル作成とスタイル設定
            actors_table = self._create_table(d, len(threat_actors),
                                              (30 * mm, 125 * mm))
            story.append(actors_table)

        # 改ページ
        story.append(PageBreak())

        # PDF 作成
        doc.build(story,
                  onFirstPage=self._first_page,
                  onLaterPages=self._last_page)
Beispiel #10
0
styles = getSampleStyleSheet()
styles.add(ParagraphStyle(name="Malgun", fontName="malgun"))
styles.add(ParagraphStyle(name="MalgunB", fontName="malgunbd"))

# Create Content
Story = []
img = 'test1.png'
d = Drawing(0,0)
i = Image(370,-410,12.5*cm,7.4*cm,img)
d.add(i)
Story.append(d)

ptext = u'<font size=24>[업무 파일 반출] %s월 %s주차 주간 보고서</font>' % ('10', '3')
Story.append(Paragraph(ptext, styles["MalgunB"]))
Story.append(Spacer(1,34))

line = MKLine(700)
Story.append(line)
Story.append(Spacer(1,12))

ptext = u'<font size=16>- %s/%s(%s) ~ %s/%s(%s) 총 %s개 사유서 발송 중 %s개 회신 (위반 %s개, 업무 %s개)</font>' % ('10', '16', '월', '10', '22', '일', '10', '9', '2', '7')
Story.append(Paragraph(ptext, styles["Malgun"]))
Story.append(Spacer(1,24))

ptext = u'<font size=14>[특이사항]</font>'
Story.append(Paragraph(ptext, styles["MalgunB"]))
Story.append(Spacer(1,12))

ptext = u'<font size=12>ㆍ유형별 반출 통계 : %s (%s) > %s (%s) > %s (%s)</font>' % ('USB', '5', 'APP', '3', 'WEB', '2')
Story.append(Paragraph(ptext, styles["Malgun"]))
Beispiel #11
0
def write_document(response, file_name, params={}):
    """Method to write to pdf from pandas."""
    try:

        # datas = pd.DataFrame(data)
        # response = '%s.pdf' % (file_name)
        STATIC_ROOT = settings.STATICFILES_DIRS[0]
        rparams = file_name.split('_')
        rid = int(rparams[3])
        region = rparams[0].replace('-', ' ')
        report_name = rparams[1].replace('-', ' ')
        if 'OU ' in region or 'ou_name' in params:
            ou_name = params['ou_name'] if 'ou_name' in params else 'DCS'
            report_name = "%s (%s)" % (report_name, ou_name)
        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
        styles.add(ParagraphStyle(name='Right', alignment=TA_RIGHT))
        styles.add(ParagraphStyle(name='Left', alignment=TA_LEFT))
        styles.add(ParagraphStyle(
            name='Line_Data', alignment=TA_LEFT, fontSize=8,
            leading=11, fontColor='#FFFFFF'))
        styles.add(ParagraphStyle(
            name='Line_Data_Small', alignment=TA_LEFT,
            fontSize=7, leading=8))
        styles.add(ParagraphStyle(
            name='Line_Data_Large', alignment=TA_LEFT,
            fontSize=12, leading=15))
        styles.add(ParagraphStyle(
            name='Line_Data_Largest', alignment=TA_LEFT,
            fontSize=14, leading=15))
        styles.add(ParagraphStyle(
            name='Line_Label', font='Helvetica-Bold',
            fontSize=7, leading=6, alignment=TA_LEFT))
        styles.add(ParagraphStyle(
            name='Line_Label1', font='Helvetica-Bold', fontSize=7,
            leading=6, alignment=TA_RIGHT))
        styles.add(ParagraphStyle(
            name='Line_Label_Center', font='Helvetica-Bold',
            fontSize=12, alignment=TA_CENTER))
        element = []
        datenow = datetime.now()
        tarehe = datenow.strftime("%d, %b %Y %I:%M %p")
        url = 'https://childprotection.go.ke'
        # ous = get_data(rid)
        # col_size = len(df.columns)
        # dt_size = len(df.index)
        # Handle headers
        address = '<b>MINISTRY OF LABOUR AND SOCIAL PROTECTION'
        address += "<br />STATE DEPARTMENT FOR SOCIAL PROTECTION"
        address += "<br />DEPARTMENT OF CHILDREN'S SERVICES</b>"
        report_number = '%s\n%s CPIMS Report\n%s' % (url, report_name, tarehe)
        # Work on the data
        start_date = ''
        end_date = datenow.strftime("%d, %B %Y")
        mon = int(datenow.strftime("%m"))
        year = int(datenow.strftime("%Y"))
        fyear = year - 1 if mon < 7 else year
        if rid in [1, 2, 4]:
            start_date = '1, July %s to ' % (fyear)
        dates = '%s%s' % (start_date, end_date)
        bar_code = BarCode(value='%s' % (report_number))
        # Logo
        logo = "%s/img/logo_gok.png" % (STATIC_ROOT)
        sd = Image(logo)
        sd.drawHeight = 0.6 * inch
        sd.drawWidth = 0.7 * inch
        data1 = [[sd, Paragraph(address, styles["Line_Data_Large"]),
                  Paragraph('CPIMS %s Report' % (region),
                            styles["Line_Data_Large"]), bar_code],
                 ['', '', Paragraph(dates,
                                    styles["Line_Label"]), '']]
        tt = Table(
            data1, colWidths=(2.1 * cm, None, 5.9 * cm, 3.4 * cm,),
            rowHeights=(1.2 * cm, .5 * cm,))

        tt.setStyle(TableStyle([
            ('INNERGRID', (2, 0), (2, 1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))
        rnote = '<b>NOTE: This is a computer generated report <br /> '
        rnote += ' as at %s.</b>' % (tarehe)
        element.append(tt)
        element.append(Spacer(0.1 * cm, .2 * cm))
        data1 = [[Paragraph('Report<br />Name:', styles["Line_Label"]),
                  Paragraph(report_name, styles["Line_Data_Largest"]),
                  Paragraph(rnote, styles["Line_Data_Small"]), ]]

        t0 = Table(data1, colWidths=(2 * cm, None, 6.1 * cm,))
        t0.setStyle(TableStyle([
            ('INNERGRID', (1, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))

        element.append(t0)
        # print(type(col_size), col_size)
        style = TableStyle(
            [('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
             ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
             ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
             ('ALIGN', (2, 3), (-1, -1), 'RIGHT'),
             ('BACKGROUND', (0, 0), (-1, 0), '#89CFF0')])
        # Configure columns
        flts = 0
        cols, idx = get_pivot_vars(rid)
        # print(len(cols), len(idx), cols, idx)
        mflts = {}
        ou_id = params['ou_id'] if 'ou_id' in params else 0
        if rid == 4:
            mflts = {'ou_id': ou_id}
        dfs, odf = create_pivot(rid, idx, cols, flts, mflts)
        # datas = np.vstack((list(dfs), np.array(dfs))).tolist()
        dt_size = len(dfs.index)
        col_size = len(dfs.columns)
        hdx = len(idx)
        rdx = len(cols)
        print('Size of Index / Columns', dt_size, col_size)
        # Now prepare the data
        if col_size > 2:
            pvt_names = list(dfs.reset_index().columns.names)
            dcols = {}
            dsize = len(dfs.columns.values)
            pvt_values = list(dfs.reset_index().columns.values)
            hd_len = len(pvt_names)
            # titles = list(pvt_values[0]) + pvt_names
            col_length = 0
            for col in pvt_values:
                col_length = len(col)
                break
            for i in range(0, col_length):
                for col in pvt_values:
                    if i not in dcols:
                        dcols[i] = [col[i]]
                    else:
                        dcols[i].append(col[i])
            fcls = []
            for fc in dcols:
                fl = dcols[fc]
                if fc == 0:
                    fcl = list(dict.fromkeys(fl))
                    nfcl = fcl + [''] * (len(fl) - len(fcl))
                    fcls.append(nfcl)
                else:
                    fcls.append(fl)
            data_list = dfs.reset_index().values.tolist()
            # data_list = [dfs.columns.values.tolist()] + dfs.values.tolist()
            # print(data_list)
            dtl, dd = [], []
            for dl in data_list:
                # dl[1] = Paragraph(dl[1], styles["Normal"])
                if dl[0] not in dd:
                    dd.append(dl[0])
                    # dl[0] = Paragraph(dl[0], styles["Normal"])
                    dtl.append(dl)
                else:
                    dl[0] = ''
                    dtl.append(dl)

            datas = fcls + dtl
            cols = get_rlcols(rid, dsize)
            # Create table style
            bs = col_size + (hdx - 1)
            ds = dt_size + (rdx)
            style = TableStyle(
                [('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                 ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
                 ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                 ('ALIGN', (hdx, hd_len), (-1, -1), 'RIGHT'),
                 # ('FONTSIZE', (0, 0), (-1, -1), 9),
                 ('FONTNAME', (0, ds), (-1, -1), 'Helvetica-Bold'),
                 ('FONTNAME', (bs, 0), (-1, -1), 'Helvetica-Bold'),
                 ('BACKGROUND', (0, 0), (-1, 0), '#89CFF0')])

            t1 = Table(datas, colWidths=cols, repeatRows=hd_len)
            t1.setStyle(style)
            element.append(t1)
        else:
            ftxt = TXT[3]
            bfooter = Paragraph(ftxt, styles["Line_Data_Largest"])
            element.append(Spacer(0.1 * cm, 1.1 * cm))
            element.append(bfooter)
        qstyle = TableStyle(
            [('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
             ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
             ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
             ('SPAN', (0, 0), (-1, 0)),
             ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
             ('FONTNAME', (0, 0), (-1, 1), 'Helvetica-Bold'),
             ('BACKGROUND', (0, 0), (-1, 0), '#89CFF0')])
        element.append(Spacer(0.1 * cm, 1.5 * cm))
        if rid == 4 and col_size > 2:
            # Add case management details
            cmdts = get_cm(rid, ou_id)
            cmsize = len(cmdts.index)
            cmgt = "This Week's Summons, Court Sessions and Discharges"
            if cmsize > 0:
                cm_values = cmdts.values.tolist()
                colw = (2.86 * cm, 4.0 * cm, 1.0 * cm, 5.0 * cm,
                        6.0 * cm, 6.0 * cm, 3.0 * cm)
                data = ["CPIMS ID", "Name / Initials", "Age", "DoB",
                        "Case Category", "Case Management", "Due Date"]
                cm_data = [[cmgt, "", "", "", "", "", ""], data]
                cm_data += cm_values
            else:
                colw = (2.86 * cm, 25.0 * cm)
                data = ["", "No data available from the System."]
                cm_data = [[cmgt, ""], data]

            t2 = Table(cm_data, colWidths=colw, repeatRows=2)
            t2.setStyle(qstyle)
            element.append(t2)
            element.append(Spacer(0.1 * cm, .5 * cm))
            ftxt = TXT[1]
            footer = Paragraph(ftxt % (cmsize), styles["Line_Data_Small"])
            element.append(footer)
            element.append(Spacer(0.1 * cm, .6 * cm))
            # Also add DQA details
            qdts = get_dqa(odf)
            qdsize = len(qdts.index)
            if qdsize > 0:
                qa_values = qdts.values.tolist()
                # print(qa_values)
                dtitle = "DQA Records for your action"
                colw = (2.86 * cm, 4.0 * cm, 1.0 * cm, 5.0 * cm, 3.0 * cm,
                        3.0 * cm, 3.0 * cm, 3.0 * cm, 3.0 * cm)
                qdata = ["CPIMS ID", "Name / Initials", "Age",
                         "Case Category", "DQA Sex", "DQA DoB",
                         "DQA Age", "Case Status", "Case Date"]
                dq_data = [[dtitle, "", "", "", "", "", "", "", ""], qdata]
                dq_data += qa_values
            else:
                colw = (2.86 * cm, 25.0 * cm)
                qdata = ["", "No data available from the System."]
                dq_data = [["DQA Records for your action", ""], qdata]
            t3 = Table(dq_data, colWidths=colw, repeatRows=2)
            t3.setStyle(qstyle)
            element.append(t3)
            element.append(Spacer(0.1 * cm, .5 * cm))
            ftxt = TXT[2]
            footer = Paragraph(ftxt % (qdsize), styles["Line_Data_Small"])
            element.append(footer)
        doc = SimpleDocTemplate(
            response, pagesize=A4, rightMargin=20,
            leftMargin=20, topMargin=30, bottomMargin=30,
            keywords="CPIMS, Child Protection in Kenya, UNICEF, DCS, <!NMA!>")
        doc.pagesize = landscape(A4)
        # doc.build(element)
        doc.watermark = 'CPIMS'
        doc.fund_name = ''
        doc.report_info = ''
        doc.source = 'Child Protection Information Management System (CPIMS)'
        doc.build(element, onFirstPage=draw_page, onLaterPages=draw_page,
                  canvasmaker=Canvas)
    except Exception as e:
        print('Error generating pdf - %s' % (e))
    else:
        pass
    def treatment_report(treatment, treatment_cycle, goniometries, perimetries,
                         muscle_tests):
        """
        Returns the list of relevant results for the searched query
        """

        pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf'))
        pdfmetrics.registerFont(TTFont('VeraBd', 'VeraBd.ttf'))
        pdfmetrics.registerFont(TTFont('VeraIt', 'VeraIt.ttf'))
        pdfmetrics.registerFont(TTFont('VeraBI', 'VeraBI.ttf'))

        sample_style_sheet = getSampleStyleSheet()
        buffer = io.BytesIO()

        my_doc = SimpleDocTemplate(buffer,
                                   rightMargin=50,
                                   leftMargin=50,
                                   topMargin=100)

        title = ParagraphStyle(name='title',
                               parent=sample_style_sheet['Heading1'],
                               fontSize=18,
                               spaceAfter=15,
                               fontName='VeraBd')
        title_topic = ParagraphStyle(name='title_topic',
                                     parent=sample_style_sheet['Heading2'],
                                     spaceAfter=30,
                                     fontName='VeraBd')
        text_title_topic = ParagraphStyle(
            name='title_topic',
            parent=sample_style_sheet['Heading2'],
            leading=17,
            fontSize=13,
            fontName='VeraBd')
        subtitle_topic = ParagraphStyle(name='subtitle_topic',
                                        parent=sample_style_sheet['Heading3'],
                                        fontName='VeraBd')
        text = ParagraphStyle(name='text',
                              parent=sample_style_sheet['BodyText'],
                              fontSize=10,
                              alignment=TA_JUSTIFY,
                              fontName='Vera')
        text_topic = ParagraphStyle(name='text_topic',
                                    parent=sample_style_sheet['BodyText'],
                                    leading=25,
                                    fontSize=12,
                                    fontName='Vera')
        horizontal_text_topic = ParagraphStyle(
            name='text_topic',
            parent=sample_style_sheet['BodyText'],
            fontSize=12,
            fontName='Vera')

        chart = ReportService.BarChart([[treatment.pain_level]], ["Dor"],
                                       width=250,
                                       height=20,
                                       graph_x=30,
                                       graph_y=20,
                                       value_min=0,
                                       value_max=10,
                                       value_step=1)
        flowables = [Paragraph("Relatório de Tratamento", title)] + [Spacer(1, 0.40 * inch)] +\
                    treatment_cycle.report(title_topic, text_topic) + treatment.report(text_title_topic, text_topic,
                                                                                       text,
                                                                                       chart.horizontal_bar_graph())

        flowables += [PageBreak(), Paragraph("Perimetrias", title_topic)]
        for perimetry in perimetries:
            chart = ReportService.BarChart([[perimetry.size]], ["Tamanho"],
                                           width=350,
                                           height=30,
                                           graph_x=30,
                                           graph_y=-5,
                                           value_min=0,
                                           value_max=200,
                                           value_step=20)
            flowables += [Indenter("1cm")] + perimetry.report(subtitle_topic, horizontal_text_topic) + \
                         chart.horizontal_bar_graph() + [Indenter("-1cm"), Spacer(1, 0.60 * inch)]

        flowables += [PageBreak(), Paragraph("Testes Musculares", title_topic)]
        for muscle_test in muscle_tests:
            chart = ReportService.BarChart([[muscle_test.strength]], ["Força"],
                                           width=350,
                                           height=30,
                                           graph_x=30,
                                           graph_y=-5,
                                           value_min=0,
                                           value_max=5,
                                           value_step=1)
            flowables += [Indenter("1cm")] + muscle_test.report(subtitle_topic, horizontal_text_topic) + \
                         chart.horizontal_bar_graph() + [Indenter("-1cm"), Spacer(1, 0.60 * inch)]

        flowables += [PageBreak(), Paragraph("Goniometrias", title_topic)]
        page_break = False
        for goniometry in goniometries:
            chart_data = [[
                goniometry.min_abduction, goniometry.min_adduction,
                goniometry.min_flexion, goniometry.min_rotation,
                goniometry.min_extension
            ],
                          [
                              goniometry.max_abduction,
                              goniometry.max_adduction, goniometry.max_flexion,
                              goniometry.max_rotation, goniometry.max_extension
                          ]]
            chart = ReportService.BarChart(
                chart_data,
                ['Abdução', 'Adução', 'Flexão', 'Rotação', 'Extensão'],
                width=350,
                height=150,
                graph_x=30,
                graph_y=65,
                value_min=0,
                value_max=180,
                value_step=20)
            flowables += [Indenter("1cm")] + goniometry.report(subtitle_topic, horizontal_text_topic) + \
                         chart.vertical_bar_chart() + [Indenter("-1cm")]

            if page_break:
                flowables += [PageBreak()]

            page_break = not page_break

        my_doc.build(flowables,
                     onFirstPage=ReportService._header_footer,
                     onLaterPages=ReportService._header_footer)

        buffer.seek(0)

        return buffer
def write_report(cs, locations, percents, in_files, des_mat, des_mat_cov,
                 subjects, meanval, imagefiles, surface_ims, thr, csize, fwhm,
                 onset_images):
    from reportlab.platypus import SimpleDocTemplate, Paragraph, Table, TableStyle, Spacer, PageBreak
    from reportlab.lib.units import inch
    from reportlab.lib.pagesizes import letter
    from reportlab.lib import colors
    import time
    from reportlab.lib.enums import TA_RIGHT
    from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
    from numpy import array
    import os
    from PIL import Image

    def get_and_scale(imagefile, scale=1):
        from reportlab.platypus import Image as Image2
        im1 = scale_im(Image.open(imagefile))
        im = Image2(imagefile, im1.size[0] * scale, im1.size[1] * scale)
        return im

    def scale_im(im):
        # scales an image so that it will fit on the page with various margins...
        width, height = letter
        newsize = array(im.size) / (max(
            array(im.size) / array([width - (1 * inch), height - (2 * inch)])))
        newsize = tuple(map(lambda x: int(x), tuple(newsize)))
        return im.resize(newsize)

    fwhm = [fwhm]
    report = os.path.join(os.getcwd(), "slice_tables.pdf")
    doc = SimpleDocTemplate(report,
                            pagesize=letter,
                            rightMargin=36,
                            leftMargin=36,
                            topMargin=72,
                            bottomMargin=72)
    elements = []
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='RIGHT', alignment=TA_RIGHT))

    formatted_time = time.ctime()

    ptext = '<font size=10>%s</font>' % formatted_time
    elements.append(Paragraph(ptext, styles["Normal"]))
    elements.append(Spacer(1, 12))

    ptext = '<font size=22>%s</font>' % ('Subject ' + subjects + ' Report')
    elements.append(Paragraph(ptext, styles["Normal"]))
    elements.append(Spacer(1, 24))

    ptext = '<font size=10>%s</font>' % ("The contrast files are: ")
    elements.append(Paragraph(ptext, styles["Normal"]))
    elements.append(Spacer(1, 12))

    contrasts = []
    for fil in in_files:
        pt = os.path.split(fil)[1]
        contrasts.append(pt)
        ptext = '<font size=10>%s</font>' % pt
        elements.append(Paragraph(ptext, styles["Normal"]))
        elements.append(Spacer(1, 12))

    ptext = '<font size=10>%s</font>' % (
        "The stat images were thresholded at z = %s and min cluster size = %s voxels. FWHM = %d "
        % (thr, csize, fwhm[0]))
    elements.append(Paragraph(ptext, styles["Normal"]))
    elements.append(Spacer(1, 12))
    elements.append(PageBreak())

    if not isinstance(des_mat, list):
        des_mat = [des_mat]
    if not isinstance(des_mat_cov, list):
        des_mat_cov = [des_mat_cov]

    for i in range(len(des_mat)):
        ptext = '<font size=10>%s</font>' % ('Design Matrix:')
        elements.append(Paragraph(ptext, styles["Normal"]))
        elements.append(Spacer(1, 12))
        im = get_and_scale(des_mat[i], .6)
        elements.append(im)
        elements.append(Spacer(1, 12))

        ptext = '<font size=10>%s</font>' % ('Covariance Matrix:')
        elements.append(Paragraph(ptext, styles["Normal"]))
        elements.append(Spacer(1, 12))
        im = get_and_scale(des_mat_cov[i], .6)
        elements.append(im)
        elements.append(PageBreak())

    if onset_images:
        for image in onset_images:
            if isinstance(image, list):
                for im0 in image:
                    im = get_and_scale(im0)
                    elements.append(im)
            else:
                im = get_and_scale(image)
                elements.append(im)

    for i, con_cs in enumerate(cs):
        data = [['Size', 'Location', 'Ratio', 'Mean(z)', 'Image']]
        for j, cluster in enumerate(con_cs[0]):
            data.append([])
            data[j + 1].append(cluster)
            locstr = ''
            perstr = ''
            if len(locations[i][j]) <= 50:
                for k, loc in enumerate(locations[i][j]):
                    locstr = locstr + loc + '\n'
                    perstr = perstr + '%.2f\n' % percents[i][j][k]

            data[j + 1].append(locstr)
            data[j + 1].append(perstr)
            meanstr = '%2.2f' % meanval[i][j]
            data[j + 1].append(meanstr)
            im = get_and_scale(imagefiles[i][j], .5)
            data[j + 1].append(im)

        print data
        t = Table(data)
        t.setStyle(
            TableStyle([('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]))
        t.hAlign = 'LEFT'
        ptext = '<font size=10>%s</font>' % ('Contrast:  %s' % (contrasts[i]))
        elements.append(Paragraph(ptext, styles["Normal"]))
        elements.append(Spacer(1, 12))
        elements.append(get_and_scale(surface_ims[i]))
        elements.append(Spacer(1, 12))
        elements.append(t)
        elements.append(Spacer(1, 12))
        #elements.append(PageBreak())

    doc.build(elements)
    return report, elements
Beispiel #14
0
            Paragraph("Image mode", styles["Small"]),
            Paragraph(imageMode, styles["Small"])
        ],
        [
            Paragraph("Image size", styles["Small"]),
            Paragraph("%s px" % imageSize, styles["Small"])
        ],
    ],
                    colWidths=[70, 234])
    imgData.setStyle(tableStyleSmall)

    t = Table([[im, imgData]], colWidths=[3 * inch + 6, 310])
    t.setStyle(tableStyleImg)
    Story.append(t)

    Story.append(Spacer(10, 20))

# ------- FileSystem Section ---------------------------------------------

if printFS:

    Story.append(Paragraph("FileSystem data", styles['Heading2']))

    stats = os.stat(filename)

    # otherTags stores data in 2 column format (tag, value)
    otherTags = []

    # attrs stores a list of attributes to append (if available) to otherTags
    # [attribute tag - attribute descr - type]
    # type:
Beispiel #15
0
 def wrap (self, aW, aH):
     w, h = Spacer.wrap(self, aW, aH)
     self.height = min(aH, h)
     return w, self.height
Beispiel #16
0
 def getFlowable(self):
     return Spacer(72, self.height)
Beispiel #17
0
# Create document 
doc = SimpleDocTemplate(fn_out ,pagesize=letter,
                        rightMargin=0.75*inch,leftMargin=0.75*inch,
                        topMargin=72,bottomMargin=18)
Story = []
t = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
styles=getSampleStyleSheet()
styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
styles.add(ParagraphStyle(name='Small', fontSize=8))
styles.add(ParagraphStyle(name='Smallish', fontSize=9))

####################### Introduction ##############################
# Title
text = 'ICON %s' % (a['data_type'].split('>')[-1][1:])
Story.append(Paragraph(text, styles["Title"]))
Story.append(Spacer(1, 12))

# Error notes
if error_notes:
    for text in error_notes:
        Story.append(Paragraph('<font color="red">%s</font>'%text, styles["Normal"]))
        Story.append(Spacer(1, 4))

# Introduction
text = """
This document describes the data product for %s, which is in NetCDF4 format.
""" % (a['description'])
Story.append(Paragraph(text, styles["Justify"]))
Story.append(Spacer(1, 12))

# Text Supplement: one paragraph per string
Beispiel #18
0
def _create_invoice(invoice_buffer, invoice, proposal):

    global DPAW_HEADER_LOGO
    #    if  cols_var["TEMPLATE_GROUP"] == 'rottnest':
    #        DPAW_HEADER_LOGO = os.path.join(settings.BASE_DIR, 'mooring', 'static', 'mooring', 'img','logo-rottnest-island-sm.png')
    #    else:
    #        DPAW_HEADER_LOGO = os.path.join(settings.BASE_DIR, 'ledger', 'payments','static', 'payments', 'img','dbca_logo.jpg')
    DPAW_HEADER_LOGO = os.path.join(settings.PROJECT_DIR, 'payments', 'static',
                                    'payments', 'img', 'dbca_logo.jpg')

    every_page_frame = Frame(PAGE_MARGIN,
                             PAGE_MARGIN + 250,
                             PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 450,
                             id='EveryPagesFrame',
                             showBoundary=0)
    remit_frame = Frame(PAGE_MARGIN,
                        PAGE_MARGIN,
                        PAGE_WIDTH - 2 * PAGE_MARGIN,
                        PAGE_HEIGHT - 600,
                        id='RemitFrame',
                        showBoundary=0)
    every_page_template = PageTemplate(id='EveryPages',
                                       frames=[every_page_frame, remit_frame],
                                       onPage=_create_header)

    doc = BaseDocTemplate(invoice_buffer,
                          pageTemplates=[every_page_template],
                          pagesize=A4)

    # this is the only way to get data into the onPage callback function
    doc.invoice = invoice
    doc.proposal = proposal
    owner = invoice.owner

    elements = []
    #elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 5))

    # Draw Products Table
    invoice_table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'),
                                      ('GRID', (0, 0), (-1, -1), 1,
                                       colors.black),
                                      ('ALIGN', (0, 0), (-1, -1), 'LEFT')])
    items = invoice.order.lines.all()

    discounts = invoice.order.basket_discounts
    if invoice.text:
        elements.append(Paragraph(invoice.text, styles['Left']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 2))
    data = [['Item', 'Product', 'Quantity', 'Unit Price', 'Total']]
    val = 1
    s = styles["BodyText"]
    s.wordWrap = 'CJK'

    for item in items:
        data.append([
            val,
            Paragraph(item.description, s), item.quantity,
            currency(item.unit_price_incl_tax),
            currency(item.line_price_before_discounts_incl_tax)
        ])
        val += 1
    # Discounts
    data.append(['', '', '', ''])
    for discount in discounts:
        data.append(
            ['', discount.offer, '', '', '-${}'.format(discount.amount)])
        val += 1
    t = Table(data,
              style=invoice_table_style,
              hAlign='LEFT',
              colWidths=(
                  0.7 * inch,
                  None,
                  0.7 * inch,
                  1.0 * inch,
                  1.0 * inch,
              ))
    elements.append(t)
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 2))
    # /Products Table
    if invoice.payment_status != 'paid' and invoice.payment_status != 'over_paid':
        elements.append(
            Paragraph(settings.INVOICE_UNPAID_WARNING, styles['Left']))

    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 6))

    # Remitttance Frame
    elements.append(FrameBreak())
    boundary = BrokenLine(PAGE_WIDTH - 2 * (PAGE_MARGIN * 1.1))
    elements.append(boundary)
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    remittance = Remittance(HEADER_MARGIN, HEADER_MARGIN - 10, proposal,
                            invoice)
    elements.append(remittance)
    #_create_remittance(invoice_buffer,doc)
    doc.build(elements)

    return invoice_buffer
Beispiel #19
0
 def append(self, data):
     self.story_arr.append(data)
     self.story_arr.append(Spacer(1, 12))
Beispiel #20
0
    def create_timesheet_layer(self, timesheet_data):
        data = timesheet_data['data']
        client = timesheet_data['client']
        date = timesheet_data['date']
        employee = timesheet_data['emp']
        description = timesheet_data['desc']

        packet = io.BytesIO()
        doc = SimpleDocTemplate(packet)

        # Create top material with number and client address
        content = [Spacer(1, 1.25 * inch)]

        content.append(
            Paragraph("<b>Date: </b>{}".format(date),
                      self.styles['to_address']))
        content.append(Spacer(1, 0.25 * inch))
        content.append(
            Paragraph("<b>Description: </b>{}".format(description),
                      self.styles['to_address']))
        content.append(Spacer(1, 0.25 * inch))

        columns = [[
            Paragraph("<b>%s</b>" % x, self.styles['table_header'])
            for x in ["Day", "Date", "Hours"]
        ]]
        list_style = TableStyle([
            ('LINEABOVE', (0, 0), (-1, 0), 1, colors.black),
            ('LINEBELOW', (0, 0), (-1, 0), 1, colors.black),
            ('BACKGROUND', (0, 0), (-1, 0), colors.grey),

            # ('ALIGN' ,(-1,1), (-1,-1), 'RIGHT'),
            ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
            ('LINEABOVE', (0, 1), (-1, -1), 0.25, colors.black),
            ('BACKGROUND', (0, -1), (-1, -1), colors.lightgrey),
            ('LINEBELOW', (0, -1), (-1, -1), 1, colors.black),
            ('LINEABOVE', (0, -1), (-1, -1), 1, colors.black),
        ])

        total = sum((Decimal(x[1]) for x in data),
                    Decimal(0)).quantize(Decimal('0.01'))

        for date, hours in data:
            columns.append([
                Paragraph(date.strftime('%a'), self.styles['table_small']),
                Paragraph(date.strftime('%d %b %Y'),
                          self.styles['table_small']),
                Paragraph(str(Decimal(hours).quantize(Decimal('0.01'))),
                          self.styles['table_small'])
            ])
        columns.append([
            '',
            Paragraph("<b>Total hours</b>", self.styles['table_small']),
            Paragraph(str(total), self.styles['table_small'])
        ])

        content.append(
            Table(columns,
                  colWidths=[50, 150, 50],
                  style=list_style,
                  hAlign='LEFT'))

        doc.build(content)
        return packet
Beispiel #21
0
    def imprimir(self):

        fec_hoy= datetime.date.today()
        hoy = fec_hoy.strftime("%d/%m/%Y")

        styleSheet=getSampleStyleSheet()
        img=Image("cabezalcaida.png",225,50)
        otro_estilo= ParagraphStyle('',fontSize = 20,textColor = '#000',leftIndent = 200,rightIndent = 50)
        style_barra= ParagraphStyle('',fontSize = 13,textColor = '#000',leftIndent = 300, rightIndent = 0)
        estilo_cabezal= ParagraphStyle('',fontSize = 15,textColor = '#000',leftIndent = 100,rightIndent = 0)

        texto_principal = ""
        estilo_texto = ParagraphStyle('',
                fontSize = 12,
                        alignment = 0,
                        spaceBefore = 0,
                        spaceAfter = 0,
            #backColor = '#fff',
            textColor = '#999',
            leftIndent = 10 )

        h = Paragraph(texto_principal, estilo_texto)
        banner = [ [ img,h ] ]
        options = QFileDialog.Options()
        story=[]
        ban = Table( banner, colWidths=0, rowHeights=10)

        story.append(ban)
        story.append(Spacer(0,15))

        P=Paragraph("<u>Registro de ingresos diarios </u> ",estilo_cabezal)
        story.append(P)
        story.append(Spacer(0,25))

        P=Paragraph("<b>Fecha:  " + str (hoy)+ " </b> ",style_barra)
        story.append(P)
        story.append(Spacer(0,5))

        integrantes = [[Paragraph('''<font size=12> <b> </b></font>''',styleSheet["BodyText"])],
                ['Nombre y Apellido', 'Cuota', 'N° Cuota','Importe', 'Punitorios','Descuento', 'Estado']]
        #pyqtRemoveInputHook()
        #import pdb; pdb.set_trace()

        for item in self.lst_ord:
            integrantes.append([str(item.nombre + ", " + item.apellido),str("cuota credito"),str(item.nro_cuota),str(round(item.monto_cobrado,2)),str(round(item.punitorios,2)), str(round(item.descuento,2)), str(item.estado_cuota)])
            t=Table(integrantes, (120,65, 60, 60,75,75,50))
            t.setStyle(TableStyle([
                               ('INNERGRID', (0,1), (-1,-1), 0.25, colors.black),
                               ('BOX', (0,1), (-1,-1), 0.25, colors.black),
                               ('BACKGROUND',(0,1),(-1,1),colors.lightgrey)
                               ]))

        story.append(t)
        story.append(Spacer(0,15))


        nombre_archivo = "Reg_ing_diarios" + str(datetime.date.today().year)+"_"+str(datetime.date.today().month) + "_" + str(datetime.date.today().day) + ".pdf"

        #---------------------------------------CAMBIAR RUTA (LA PALABRA slam2016 POR LA RUTA DESEADA DE LA PC)------------------------------------------------#
        file_path ="/home/slam2016/Documentos/credired/credired20170306/pdf/ingresos/ingresos"+str(datetime.date.today().year)+"_"+str(datetime.date.today().month)


        if not os.path.exists(file_path):
            os.makedirs(file_path)

        doc=SimpleDocTemplate(file_path +"/" + nombre_archivo)
        doc.build(story)
        if doc:
            msgBox = QMessageBox()
            msgBox.setWindowTitle("Correcto")
            msgBox.setText( 'Se genero el informe correctamente : ' + nombre_archivo)
            msgBox.exec_()

        if sys.platform == 'linux':
            subprocess.call(["xdg-open", file_path +"/" + nombre_archivo])
        else:
            os.startfile( file_path +"/" + nombre_archivo)
Beispiel #22
0
    def create_invoice_layer(self, invoice_data):
        client_address = invoice_data['client_address'].encode('utf-8').decode(
            'unicode_escape')
        bank_details = invoice_data['bank_details'].encode('utf-8').decode(
            'unicode_escape')
        date = invoice_data['date']
        number = invoice_data['number']
        particulars = invoice_data['particulars']
        data_columns = invoice_data['columns']
        footers = invoice_data['footers']
        taxes = invoice_data['taxes']
        signatory = invoice_data['signatory']
        bill_unit = invoice_data['bill_unit']

        # create a new PDF with Reportlab
        packet = io.BytesIO()
        doc = SimpleDocTemplate(packet)

        # Create top material with number and client address
        content = [Spacer(1, 2 * inch)]
        content.append(
            Paragraph("<b>Date: </b>{}".format(date),
                      self.styles['to_address']))
        content.append(Spacer(1, 0.25 * inch))
        content.append(
            Paragraph("<b>Invoice Number: </b>{}".format(number),
                      self.styles['to_address']))
        content.append(Spacer(1, 0.25 * inch))
        content.append(Paragraph("<b>Bill to:</b>", self.styles['to_address']))
        for i in client_address.split("\n"):
            content.append(Paragraph(i, self.styles['to_address']))
        content.append(Spacer(1, 0.5 * inch))
        content.append(
            Paragraph("<b>Subject: </b>{}".format(particulars),
                      self.styles['to_address']))

        # Now the table headers
        headers = invoice_data['fields']
        columns = [[
            Paragraph("<b>%s</b>" % x, self.styles['regular']) for x in headers
        ]]

        list_style = TableStyle([
            ('LINEABOVE', (0, 0), (-1, 0), 1, colors.black),
            ('LINEBELOW', (0, 0), (-1, 0), 1, colors.black),
            ('BACKGROUND', (0, 0), (-1, 0), colors.grey),
            ('BACKGROUND', (-1, 1), (-1, -1), colors.lightgrey),
            ('ALIGN', (-1, 1), (-1, -1), 'RIGHT'),
            ('LINEABOVE', (0, 1), (-1, -1), 0.25, colors.black),
            ('LINEBELOW', (0, -1), (-1, -1), 1, colors.black),
            ('LINEABOVE', (0, -1), (-1, -1), 1, colors.black),
        ])

        total = Decimal(0)
        content.append(Spacer(1, 0.1 * inch))
        for i in data_columns:
            if i[-1]:
                total += Decimal(i[-1])
                i[-1] = "{} {}".format(str(i[-1]), bill_unit)
            columns.append(
                Paragraph(str(t), self.styles['regular']) for t in i)

        extra_vals = dict(net_total=total)
        for t, v in taxes.items():
            n = total * Decimal(v)
            extra_vals[t] = n.quantize(Decimal('0.01'))

        extra_vals['gross_total'] = sum(extra_vals.values())

        for i in footers:
            c1 = []
            i[-1] = "{} {}".format(str(i[-1]), bill_unit)
            for j in i:
                j = j.format(**extra_vals)
                if j.startswith("b:"):
                    c1.append(
                        Paragraph("<b>{}</b>".format(j.replace("b:", "")),
                                  self.styles['regular']))
                else:
                    c1.append(Paragraph(str(j), self.styles['regular']))
            columns.append(c1)

        content.append(Table(columns, style=list_style))

        content.append(Spacer(1, 0.5 * inch))
        content.append(
            Paragraph("<b>Payment details:</b>", self.styles['to_address']))
        for i in bank_details.split("\n"):
            content.append(Paragraph(i, self.styles['to_address']))

        content.append(Spacer(1, 0.25 * inch))
        content.append(
            Paragraph("Sincerely,                                  ",
                      self.styles['regular']))
        content.append(Spacer(1, 0.5 * inch))
        content.append(
            Paragraph("{}                                  ".format(signatory),
                      self.styles['regular']))

        doc.build(content)
        return packet
from reportlab.platypus import (Paragraph, SimpleDocTemplate, Spacer)
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.pagesizes import letter
from custom_graph.CanvasFigure import CanvasFigure

doc = SimpleDocTemplate("ignore/custom_graph.pdf", pagesize=letter)
style = getSampleStyleSheet()
story = []
p = Paragraph("This is a table. " * 10, style['Normal'])
story.append(p)
dataX = [1, 2, 3, 4, 5]
dataY = [1, 2, 3, 4, 5]
graph = CanvasFigure(dataX, dataY, width=500, height=250)
story.append(graph)
story.append(p)
s = Spacer(width=0, height=60)
doc.build(story)
Beispiel #24
0
def form_01(request_data):
    """
    Форма 003/у - cстационарная карта
    """

    num_dir = request_data["dir_pk"]
    direction_obj = Napravleniya.objects.get(pk=num_dir)
    hosp_nums_obj = hosp_get_hosp_direction(num_dir)
    hosp_nums = f"- {hosp_nums_obj[0].get('direction')}"

    ind_card = direction_obj.client
    patient_data = ind_card.get_data_individual()

    hospital: Hospitals = request_data["hospital"]

    hospital_name = hospital.safe_short_title
    hospital_address = hospital.safe_address
    hospital_kod_ogrn = hospital.safe_ogrn

    if sys.platform == 'win32':
        locale.setlocale(locale.LC_ALL, 'rus_rus')
    else:
        locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8')

    pdfmetrics.registerFont(
        TTFont('PTAstraSerifBold',
               os.path.join(FONTS_FOLDER, 'PTAstraSerif-Bold.ttf')))
    pdfmetrics.registerFont(
        TTFont('PTAstraSerifReg',
               os.path.join(FONTS_FOLDER, 'PTAstraSerif-Regular.ttf')))

    buffer = BytesIO()
    doc = SimpleDocTemplate(buffer,
                            pagesize=A4,
                            leftMargin=20 * mm,
                            rightMargin=12 * mm,
                            topMargin=6 * mm,
                            bottomMargin=4 * mm,
                            allowSplitting=1,
                            title="Форма {}".format("003/у"))
    width, height = portrait(A4)
    styleSheet = getSampleStyleSheet()
    style = styleSheet["Normal"]
    style.fontName = "PTAstraSerifReg"
    style.fontSize = 12
    style.leading = 15
    style.spaceAfter = 0.5 * mm

    styleLead = deepcopy(style)
    styleLead.leading = 12
    styleLead.alignment = TA_JUSTIFY

    styleBold = deepcopy(style)
    styleBold.fontName = "PTAstraSerifBold"
    styleCenter = deepcopy(style)
    styleCenter.alignment = TA_CENTER
    styleCenter.fontSize = 12
    styleCenter.leading = 15
    styleCenter.spaceAfter = 1 * mm
    styleCenterBold = deepcopy(styleBold)
    styleCenterBold.alignment = TA_CENTER
    styleCenterBold.fontSize = 12
    styleCenterBold.leading = 15
    styleCenterBold.face = 'PTAstraSerifBold'
    styleCenterBold.borderColor = black
    styleJustified = deepcopy(style)
    styleJustified.alignment = TA_JUSTIFY
    styleJustified.spaceAfter = 4.5 * mm
    styleJustified.fontSize = 12
    styleJustified.leading = 4.5 * mm

    styleRight = deepcopy(styleJustified)
    styleRight.alignment = TA_RIGHT

    objs = []

    styleT = deepcopy(style)
    styleT.alignment = TA_LEFT
    styleT.fontSize = 10
    styleT.leading = 4.5 * mm
    styleT.face = 'PTAstraSerifReg'

    print_district = ''
    if SettingManager.get("district", default='True', default_type='b'):
        if ind_card.district is not None:
            print_district = 'Уч: {}'.format(ind_card.district.title)

    opinion = [
        [
            Paragraph(
                '<font size=11>{}<br/>Адрес: {}<br/>ОГРН: {} <br/><u>{}</u> </font>'
                .format(hospital_name, hospital_address, hospital_kod_ogrn,
                        print_district), styleT),
            Paragraph(
                '<font size=9 >Код формы по ОКУД:<br/>Код организации по ОКПО: 31348613<br/>'
                'Медицинская документация<br/>форма № 003/у</font>', styleT),
        ],
    ]

    tbl = Table(opinion, 2 * [90 * mm])
    tbl.setStyle(
        TableStyle([
            ('GRID', (0, 0), (-1, -1), 0.75, colors.white),
            ('LEFTPADDING', (1, 0), (-1, -1), 80),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ]))

    objs.append(tbl)
    space_symbol = '&nbsp;'
    if patient_data['age'] < SettingManager.get(
            "child_age_before", default='15', default_type='i'):
        patient_data['serial'] = patient_data['bc_serial']
        patient_data['num'] = patient_data['bc_num']
    else:
        patient_data['serial'] = patient_data['passport_serial']
        patient_data['num'] = patient_data['passport_num']

    p_phone = ''
    if patient_data['phone']:
        p_phone = 'тел.: ' + ", ".join(patient_data['phone'])

    p_address = patient_data['main_address']
    work_place = patient_data['work_place_db'] if patient_data[
        'work_place_db'] else patient_data['work_place']
    p_work = work_place

    card_num_obj = patient_data['card_num'].split(' ')
    p_card_num = card_num_obj[0]

    # взять самое последнее направленеие из hosp_dirs
    hosp_last_num = hosp_nums_obj[-1].get('direction')
    ############################################################################################################
    # Получение данных из выписки
    # Взять услугу типа выписка. Из полей "Дата выписки" - взять дату. Из поля "Время выписки" взять время
    hosp_extract_data = hosp_extract_get_data(hosp_last_num)

    extrac_date, extract_time, final_diagnos, other_diagnos, near_diagnos, outcome, doc_fio, manager_depart, room_num, depart_extract = '', '', '', '', '', '', '', '', '', ''
    days_count = '__________________________'

    if hosp_extract_data:
        extrac_date = hosp_extract_data['date_value']
        extract_time = hosp_extract_data['time_value']
        final_diagnos = hosp_extract_data['final_diagnos']
        other_diagnos = hosp_extract_data['other_diagnos']
        near_diagnos = hosp_extract_data['near_diagnos']
        days_count = hosp_extract_data['days_count']
        if hosp_extract_data['outcome']:
            outcome = hosp_extract_data['outcome'] + ' (' + hosp_extract_data[
                'result_hospital'] + ')'
        doc_fio = hosp_extract_data['doc_fio']
        manager_depart = hosp_extract_data['manager_depart']
        room_num = hosp_extract_data['room_num']
        iss_last_hosp = Issledovaniya.objects.filter(
            napravleniye__pk=hosp_last_num)[0]
        depart_extract = iss_last_hosp.research.title

    # Получить отделение - из названия услуги или самого главного направления
    hosp_depart = hosp_nums_obj[0].get('research_title')

    ############################################################################################################
    # Получить данные из первичного приема (самого первого hosp-направления)
    hosp_first_num = hosp_nums_obj[0].get('direction')
    primary_reception_data = primary_reception_get_data(hosp_first_num)

    ###########################################################################################################
    # Получение данных группы крови
    fcaction_avo_id = Fractions.objects.filter(
        title='Групповая принадлежность крови по системе АВО').first()
    fcaction_rezus_id = Fractions.objects.filter(title='Резус').first()
    group_blood_avo = get_fraction_result(ind_card.pk,
                                          fcaction_avo_id.pk,
                                          count=1)
    if group_blood_avo:
        group_blood_avo_value = group_blood_avo[0][5]
    else:
        group_blood_avo_value = primary_reception_data['blood_group']
    group_blood_rezus = get_fraction_result(ind_card.pk,
                                            fcaction_rezus_id.pk,
                                            count=1)
    if group_blood_rezus:
        group_rezus_value = group_blood_rezus[0][5].replace('<br/>', ' ')
    else:
        group_rezus_value = primary_reception_data['resus_factor']

    ###########################################################################################################
    # получение данных клинического диагноза
    clinical_diagnos = hosp_get_clinical_diagnos(hosp_nums_obj)

    #####################################################################################################
    # получить даные из переводного эпикриза: Дата перевода, Время перевода, в какое отделение переведен
    # у каждого hosp-направления найти подчиненное эпикриз Перевод*
    transfers_data = hosp_get_transfers_data(hosp_nums_obj)
    transfers = ''
    for i in transfers_data:
        transfers = f"{transfers} в {i['transfer_research_title']} {i['date_transfer_value']}/{i['time_transfer_value']};"

    #####################################################################################################
    title_page = [
        Indenter(left=0 * mm),
        Spacer(1, 8 * mm),
        Paragraph(
            '<font fontname="PTAstraSerifBold" size=15>МЕДИЦИНСКАЯ КАРТА № {} <u>{}</u>, <br/> стационарного больного</font>'
            .format(p_card_num, hosp_nums), styleCenter),
        Spacer(1, 2 * mm),
        Spacer(1, 2 * mm),
        Spacer(1, 2 * mm),
        Paragraph(
            'Дата и время поступления: {} - {}'.format(
                primary_reception_data['date_entered_value'],
                primary_reception_data['time_entered_value']), style),
        Spacer(1, 0.5 * mm),
        Paragraph(
            'Дата и время выписки: {} - {}'.format(extrac_date, extract_time),
            style),
        Spacer(1, 0.5 * mm),
        Paragraph('Отделение: {}'.format(hosp_depart), style),
        Spacer(1, 0.5 * mm),
        Paragraph(f"Палата №: {room_num} {depart_extract}", style),
        Spacer(1, 0.5 * mm),
        Paragraph('Переведен в отделение:', style),
        Spacer(1, 8 * mm),
        Paragraph('Проведено койко-дней: {}'.format(days_count), style),
        Spacer(1, 0.5 * mm),
        Paragraph(
            'Виды транспортировки(на каталке, на кресле, может идти): {}'.
            format(primary_reception_data['type_transport']), style),
        Spacer(1, 0.5 * mm),
        Paragraph(
            'Группа крови: {}. Резус-принадлежность: {}'.format(
                group_blood_avo_value, group_rezus_value), style),
        Spacer(1, 1 * mm),
        Paragraph('Побочное действие лекарств(непереносимость):', style),
        Spacer(1, 12 * mm),
        Paragraph("1. Фамилия, имя, отчество:&nbsp;", style),
        Spacer(1, 2 * mm),
        Paragraph(
            '2. Пол: {} {} 3. Дата рождения: {}'.format(
                patient_data['sex'], 3 * space_symbol, patient_data['born']),
            style),
        Spacer(1, 0.5 * mm),
        Paragraph('4. Постоянное место жительства: ', style),
        Spacer(1, 3.5 * mm),
        Paragraph('5. Место работы, профессия или должность:', style),
        Spacer(1, 0.5 * mm),
        Paragraph('6. Кем направлен больной:', style),
        Spacer(1, 0.5 * mm),
        Paragraph(
            '7. Доставлен в стационар по экстренным показаниям: {}'.format(
                primary_reception_data['extra_hospital']), style),
        Spacer(1, 0.5 * mm),
        Paragraph(
            ' через: {} после начала заболевания, получения травмы; '.format(
                primary_reception_data['time_start_ill']), style),
        Spacer(1, 0.5 * mm),
        Paragraph(
            ' госпитализирован в плановом порядке (подчеркнуть) {}.'.format(
                primary_reception_data['plan_hospital']), style),
        Spacer(1, 0.5 * mm),
        Paragraph('8. Диагноз направившего учреждения:', style),
        Spacer(1, 8 * mm),
        Paragraph('9. Диагноз при поступлении:', style),
        Spacer(1, 10 * mm),
        Paragraph('10. Диагноз клинический:', style),
        PageBreak(),
    ]

    closed_bl_result = closed_bl(hosp_nums_obj[0].get('direction'))
    data_bl = ''
    if closed_bl_result['start_date'] and closed_bl_result[
            'end_date'] and closed_bl_result['num']:
        data_bl = (
            f"<br/>открыт <u>{closed_bl_result['start_date']}</u>{5 * space_symbol}закрыт: <u>{closed_bl_result['end_date']}</u> {3 * space_symbol}"
            f"к труду: <u>{closed_bl_result['start_work']}</u> <br/>Номер ЛН: <u>{closed_bl_result['num']}</u> Выдан кому: {closed_bl_result['who_get']} "
        )

    second_page = [
        Spacer(1, 2 * mm),
        Paragraph('11. Диагноз заключительный клинический:', style),
        Spacer(1, 0.5 * mm),
        Paragraph('а) основной:', style),
        Spacer(1, 45 * mm),
        Paragraph('б) осложнение основного:', style),
        Spacer(1, 18 * mm),
        Paragraph('в) сопутствующий:', style),
        Spacer(1, 19 * mm),
        Paragraph(
            '12. Госпитализирован в данном году по поводу данного заболевания: {}, <br/>'
            'всего  - {} раз.:'.format(
                primary_reception_data['what_time_hospitalized'],
                primary_reception_data['all_hospitalized']),
            styleLead,
        ),
        Spacer(1, 1 * mm),
        Paragraph(
            '13. Хирургические операции, методы обезболивания и послеоперационные осложнения:',
            styleLead),
        Spacer(1, 40 * mm),
        Paragraph(
            '14. Другие виды лечения:___________________________________________',
            styleLead),
        Spacer(1, 0.2 * mm),
        Paragraph('для больных злокачественными новообразованиями.',
                  styleLead),
        Spacer(1, 0.2 * mm),
        Paragraph(
            ' 1.Специальное лечение: хирургическое(дистанционная гамматерапия, рентгенотерапия, быстрые '
            'электроны, контактная и дистанционная гамматерапия, контактная гамматерапия и глубокая '
            'рентгенотерапия); комбинированное(хирургическое и гамматерапия, хирургическое и рентгено - '
            'терапия, хирургическое и сочетанное лучевое); химиопрепаратами, гормональными препаратами.',
            styleLead,
        ),
        Spacer(1, 1 * mm),
        Paragraph('2. Паллиативное', styleLead),
        Spacer(1, 0.2 * mm),
        Paragraph('3. Симптоматическое лечение.', styleLead),
        Spacer(1, 0.2 * mm),
        Paragraph(f"15. Отметка о выдаче листка нетрудоспособности:{data_bl}",
                  styleLead),
        Spacer(1, 1 * mm),
        Paragraph('16. Исход заболевания: {}'.format(outcome), styleLead),
        Spacer(1, 1 * mm),
        Paragraph(
            '17.  Трудоспособность восстановлена полностью, снижена, временно утрачена, стойко утрачена в связи '
            'с данным заболеванием, с другими причинами(подчеркнуть): {}'.
            format(''),
            styleLead,
        ),
        Spacer(1, 1 * mm),
        Paragraph(
            '18. Для поступивших на экспертизу - заключение:___________________',
            styleLead),
        Spacer(1, 1 * mm),
        Paragraph(
            '___________________________________________________________________',
            styleLead),
        Spacer(1, 1 * mm),
        Paragraph('19. Особые отметки', style),
        Spacer(1, 2 * mm),
        Paragraph('Лечащий врач: {}'.format(doc_fio), style),
        Paragraph('Заведующий отделением: {}'.format(manager_depart), style),
    ]
    if primary_reception_data['weight']:
        second_page.append(
            Paragraph(f"Вес: {primary_reception_data['weight']}", styleRight))
    objs.extend(title_page)
    objs.extend(second_page)

    closed_bl_result = closed_bl(hosp_nums_obj[0].get('direction'))

    def first_pages(canvas, document):
        canvas.saveState()
        if closed_bl_result.get('is_closed', None):
            canvas.setFont('PTAstraSerifBold', 12)
            canvas.drawString(7 * mm, 290 * mm, 'ЛН')
        # Переведен
        transfers_text = [Paragraph('{}'.format(transfers), styleJustified)]
        transfers_frame = Frame(27 * mm,
                                206 * mm,
                                175 * mm,
                                7 * mm,
                                leftPadding=0,
                                bottomPadding=0,
                                rightPadding=0,
                                topPadding=0,
                                id='diagnos_frame',
                                showBoundary=0)
        transfers_inframe = KeepInFrame(
            175 * mm,
            12 * mm,
            transfers_text,
            hAlign='LEFT',
            vAlign='TOP',
        )
        transfers_frame.addFromList([transfers_inframe], canvas)

        # Побочное действие лекарств(непереносимость) координаты
        medicament_text = [
            Paragraph(
                '{}'.format(primary_reception_data['medicament_allergy']),
                styleJustified)
        ]
        medicament_frame = Frame(27 * mm,
                                 171 * mm,
                                 175 * mm,
                                 9 * mm,
                                 leftPadding=0,
                                 bottomPadding=0,
                                 rightPadding=0,
                                 topPadding=0,
                                 id='diagnos_frame',
                                 showBoundary=0)
        medicament_inframe = KeepInFrame(
            175 * mm,
            12 * mm,
            medicament_text,
            hAlign='LEFT',
            vAlign='TOP',
        )
        medicament_frame.addFromList([medicament_inframe], canvas)

        # ФИО
        fio_text = [
            Paragraph(
                "<font size=11.7 fontname ='PTAstraSerifBold'> {}</font> ".
                format(patient_data['fio']), style)
        ]
        fio_frame = Frame(77 * mm,
                          159 * mm,
                          125 * mm,
                          8 * mm,
                          leftPadding=0,
                          bottomPadding=0,
                          rightPadding=0,
                          topPadding=0,
                          id='diagnos_frame',
                          showBoundary=0)
        fio_inframe = KeepInFrame(
            175 * mm,
            12 * mm,
            fio_text,
            hAlign='LEFT',
            vAlign='TOP',
        )
        fio_frame.addFromList([fio_inframe], canvas)

        # Постоянное место жительства
        live_text = [Paragraph('{}, {}'.format(p_address, p_phone), style)]
        live_frame = Frame(88 * mm,
                           144 * mm,
                           115 * mm,
                           9 * mm,
                           leftPadding=0,
                           bottomPadding=0,
                           rightPadding=0,
                           topPadding=0,
                           id='diagnos_frame',
                           showBoundary=0)
        live_inframe = KeepInFrame(
            175 * mm,
            12 * mm,
            live_text,
            hAlign='LEFT',
            vAlign='TOP',
        )
        live_frame.addFromList([live_inframe], canvas)

        # Место работы
        work_text = [Paragraph('{}'.format(p_work), style)]
        work_frame = Frame(108 * mm,
                           138.5 * mm,
                           95 * mm,
                           5 * mm,
                           leftPadding=0,
                           bottomPadding=0,
                           rightPadding=0,
                           topPadding=0,
                           id='diagnos_frame',
                           showBoundary=0)
        work_inframe = KeepInFrame(
            175 * mm,
            12 * mm,
            work_text,
            hAlign='LEFT',
            vAlign='TOP',
        )
        work_frame.addFromList([work_inframe], canvas)

        # Кем направлен больной
        who_directed_text = [
            Paragraph('{}'.format(primary_reception_data['who_directed']),
                      style)
        ]
        who_directed_frame = Frame(77 * mm,
                                   129.5 * mm,
                                   126 * mm,
                                   7 * mm,
                                   leftPadding=0,
                                   bottomPadding=0,
                                   rightPadding=0,
                                   topPadding=0,
                                   id='diagnos_frame',
                                   showBoundary=0)
        who_directed_inframe = KeepInFrame(
            175 * mm,
            12 * mm,
            who_directed_text,
            hAlign='LEFT',
            vAlign='TOP',
        )
        who_directed_frame.addFromList([who_directed_inframe], canvas)

        # Диагноз направившего учреждения координаты
        diagnos_directed_text = [
            Paragraph(
                '{}'.format(primary_reception_data['diagnos_who_directed']),
                styleJustified)
        ]
        diagnos_directed_frame = Frame(27 * mm,
                                       98 * mm,
                                       175 * mm,
                                       9 * mm,
                                       leftPadding=0,
                                       bottomPadding=0,
                                       rightPadding=0,
                                       topPadding=0,
                                       id='diagnos_frame',
                                       showBoundary=0)
        diagnos_directed_inframe = KeepInFrame(
            175 * mm,
            10 * mm,
            diagnos_directed_text,
            hAlign='LEFT',
            vAlign='TOP',
        )
        diagnos_directed_frame.addFromList([diagnos_directed_inframe], canvas)

        # Диагноз при поступлении координаты
        diagnos_entered_text = [
            Paragraph('{}'.format(primary_reception_data['diagnos_entered']),
                      styleJustified)
        ]
        diagnos_entered_frame = Frame(27 * mm,
                                      83 * mm,
                                      175 * mm,
                                      10 * mm,
                                      leftPadding=0,
                                      bottomPadding=0,
                                      rightPadding=0,
                                      topPadding=0,
                                      id='diagnos_frame',
                                      showBoundary=0)
        diagnos_entered_inframe = KeepInFrame(
            175 * mm,
            10 * mm,
            diagnos_entered_text,
            hAlign='LEFT',
            vAlign='TOP',
        )
        diagnos_entered_frame.addFromList([diagnos_entered_inframe], canvas)

        # клинический диагноз координаты
        diagnos_text = [
            Paragraph('{}'.format(clinical_diagnos), styleJustified)
        ]
        diagnos_frame = Frame(27 * mm,
                              22 * mm,
                              175 * mm,
                              55 * mm,
                              leftPadding=0,
                              bottomPadding=0,
                              rightPadding=0,
                              topPadding=0,
                              id='diagnos_frame',
                              showBoundary=0)
        diagnos_inframe = KeepInFrame(175 * mm, 55 * mm, diagnos_text)
        diagnos_frame.addFromList([diagnos_inframe], canvas)

        # представитель пациента
        p_agent = None
        agent_status = ''
        agent = ''
        if ind_card.who_is_agent:
            p_agent = getattr(ind_card, ind_card.who_is_agent)
            agent_status = ind_card.get_who_is_agent_display()
        if p_agent:
            agent_data = p_agent.get_data_individual()
            agent_fio = agent_data['fio']
            agent_phone = ','.join(agent_data['phone'])
            agent = f"{agent_status}: {agent_fio}, тел.:{agent_phone}"

        agent_text = [Paragraph('<u>{}</u>'.format(agent), styleRight)]
        agent_frame = Frame(27 * mm,
                            5 * mm,
                            175 * mm,
                            7 * mm,
                            leftPadding=0,
                            bottomPadding=0,
                            rightPadding=0,
                            topPadding=0,
                            id='diagnos_frame',
                            showBoundary=0)
        agent_inframe = KeepInFrame(175 * mm, 10 * mm, agent_text)
        agent_frame.addFromList([agent_inframe], canvas)
        canvas.restoreState()

    # Получить все услуги из категории операции
    styleTO = deepcopy(style)
    styleTO.alignment = TA_LEFT
    styleTO.firstLineIndent = 0
    styleTO.fontSize = 9.5
    styleTO.leading = 10
    styleTO.spaceAfter = 0.2 * mm

    # Таблица для операции
    opinion_oper = [[
        Paragraph('№', styleTO),
        Paragraph('Название операции', styleTO),
        Paragraph('Дата, &nbsp час', styleTO),
        Paragraph('Метод обезболивания', styleTO),
        Paragraph('Осложнения', styleTO),
        Paragraph('Оперировал', styleTO),
    ]]

    hosp_operation = hosp_get_operation_data(num_dir)
    x = 0
    operation_result = []
    for i in hosp_operation:
        operation_template = [''] * 6
        x += 1
        operation_template[0] = Paragraph(str(x), styleTO)
        operation_template[1] = Paragraph(
            f"{i['name_operation']} <br/><font face=\"PTAstraSerifBold\" size=\"8.7\">({i['category_difficult']})</font>",
            styleTO)
        operation_template[2] = Paragraph(
            i['date'] + '<br/>' + i['time_start'] + '-' + i['time_end'],
            styleTO)
        operation_template[3] = Paragraph(i['anesthesia method'], styleTO)
        operation_template[4] = Paragraph(i['complications'], styleTO)
        operation_template[5] = Paragraph(i['doc_fio'], styleTO)
        operation_result.append(operation_template.copy())

    opinion_oper.extend(operation_result)

    t_opinion_oper = opinion_oper.copy()
    tbl_o = Table(
        t_opinion_oper,
        colWidths=(
            7 * mm,
            62 * mm,
            25 * mm,
            30 * mm,
            15 * mm,
            45 * mm,
        ),
    )
    tbl_o.setStyle(
        TableStyle([
            ('GRID', (0, 0), (-1, -1), 1.0, colors.black),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 2.1 * mm),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))

    def later_pages(canvas, document):
        canvas.saveState()
        # Заключительные диагнозы
        # Основной заключительный диагноз
        final_diagnos_text = [
            Paragraph('{}'.format(final_diagnos), styleJustified)
        ]
        final_diagnos_frame = Frame(27 * mm,
                                    230 * mm,
                                    175 * mm,
                                    45 * mm,
                                    leftPadding=0,
                                    bottomPadding=0,
                                    rightPadding=0,
                                    topPadding=0,
                                    showBoundary=0)
        final_diagnos_inframe = KeepInFrame(
            175 * mm,
            50 * mm,
            final_diagnos_text,
            hAlign='LEFT',
            vAlign='TOP',
        )
        final_diagnos_frame.addFromList([final_diagnos_inframe], canvas)

        # Осложнения основного заключительного диагноза
        other_diagnos_text = [
            Paragraph('{}'.format(other_diagnos), styleJustified)
        ]
        other_diagnos_frame = Frame(27 * mm,
                                    205 * mm,
                                    175 * mm,
                                    20 * mm,
                                    leftPadding=0,
                                    bottomPadding=0,
                                    rightPadding=0,
                                    topPadding=0,
                                    showBoundary=0)
        other_diagnos_inframe = KeepInFrame(
            175 * mm,
            20 * mm,
            other_diagnos_text,
            hAlign='LEFT',
            vAlign='TOP',
        )
        other_diagnos_frame.addFromList([other_diagnos_inframe], canvas)

        # Сопутствующие основного заключительного диагноза
        near_diagnos_text = [
            Paragraph(
                '{}'.format(
                    near_diagnos.replace('<', '&lt;').replace('>', '&gt;')),
                styleJustified)
        ]
        near_diagnos_frame = Frame(27 * mm,
                                   181 * mm,
                                   175 * mm,
                                   20 * mm,
                                   leftPadding=0,
                                   bottomPadding=0,
                                   rightPadding=0,
                                   topPadding=0,
                                   showBoundary=0)
        near_diagnos_inframe = KeepInFrame(
            175 * mm,
            20 * mm,
            near_diagnos_text,
            vAlign='TOP',
        )
        near_diagnos_frame.addFromList([near_diagnos_inframe], canvas)

        # Таблица операции
        operation_text = [tbl_o]
        operation_frame = Frame(22 * mm,
                                123 * mm,
                                170 * mm,
                                40 * mm,
                                leftPadding=0,
                                bottomPadding=0,
                                rightPadding=0,
                                topPadding=0,
                                showBoundary=0)
        operation_inframe = KeepInFrame(175 * mm,
                                        40 * mm,
                                        operation_text,
                                        hAlign='CENTRE',
                                        vAlign='TOP',
                                        fakeWidth=False)
        operation_frame.addFromList([operation_inframe], canvas)

        canvas.setFont('PTAstraSerifBold', 8)
        hospital: Hospitals = request_data["hospital"]

        hospital_name = hospital.safe_short_title

        canvas.drawString(55 * mm, 12 * mm, '{}'.format(hospital_name))
        canvas.drawString(
            55 * mm, 9 * mm,
            '№ карты : {}; Номер истории: {}'.format(p_card_num, hosp_nums))
        canvas.drawString(
            55 * mm, 6 * mm, 'Пациент: {} {}'.format(patient_data['fio'],
                                                     patient_data['born']))
        canvas.line(55 * mm, 11.5 * mm, 200 * mm, 11.5 * mm)

        canvas.restoreState()

    doc.build(objs, onFirstPage=first_pages, onLaterPages=later_pages)
    pdf = buffer.getvalue()
    buffer.close()

    return pdf
Beispiel #25
0
 def encabezado(self):
     p = Paragraph("Compras realizadas durante la semana", self.estiloPC())
     self.story.append(p)
     self.story.append(Spacer(1, 0.5 * inch))
def create_invoice(inv: Invoice) -> None:
    """
    Generates the reportlab pdf invoice
    """
    vendor = inv.vendor
    payer = inv.payer
    service = inv.services[0]
    unit_price = inv.services[1]
    amount = inv.services[2]
    total_bt = float(inv.services[1]) * float(inv.services[2])
    vat = vendor.info['vat_rate']
    total_at = (total_bt * float(vendor.info['vat_rate'])) + total_bt

    title = f'Invoice'
    vendor_name = vendor.name
    vendor_address = vendor.address
    vendor_phone = vendor.info['phone']
    vendor_email = vendor.info['email']

    payer_name = payer.name
    payer_address = payer.address
    payer_phone = payer.info['phone']
    payer_email = payer.info['email']

    due = f'This invoice is due in: {inv.info["due"]}'

    # creating the doc structure:
    doc = SimpleDocTemplate(f'../Invoices/invoice.pdf',
                            pagesize=letter,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=72,
                            bottomMargin=18,
                            title=f'Invoice for Payment',
                            author='XYZ Accountants')

    invoice_data = [
        ('Payer', 'Vendor'),
        (payer_name, vendor_name),
        (payer_address, vendor_address),
        (payer_phone, vendor_phone),
        (payer_email, vendor_email),
    ]
    t = Table(invoice_data, colWidths=4 * inch)
    t.setStyle(
        TableStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('TEXTCOLOR', (0, 0), (1, 0), blue)]))

    sec_table = [('Services Rendered', 'Unit Price', 'Amount', 'Net', 'Vat',
                  'Gross'),
                 (service, unit_price, amount, total_bt, vat, total_at)]
    s_t = Table(sec_table, colWidths=1.3 * inch)
    s_t.setStyle(
        TableStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('LINEABOVE', (0, 1), (-1, 1), 1, black)]))

    styles = getSampleStyleSheet()  # for the styles used in the document.
    story = [
        Paragraph(title, styles['Title']),
        Spacer(1, 12), t,
        Spacer(1, 12),
        Spacer(1, 12),
        Spacer(1, 12), s_t,
        Spacer(1, 12),
        Spacer(1, 12),
        Spacer(1, 12),
        Spacer(1, 12),
        Spacer(1, 12),
        Spacer(1, 12),
        Paragraph(due, styles['BodyText'])
    ]
    doc.build(story)
Beispiel #27
0
def export_pdf_log(request,
                   pk,
                   images=False,
                   comments=False,
                   uidb64=None,
                   token=None):
    '''
    Show the workout schedule
    '''
    user = request.user

    comments = bool(int(comments))
    images = bool(int(images))

    # Load the workout
    if uidb64 is not None and token is not None:
        if check_token(uidb64, token):
            schedule = get_object_or_404(Schedule, pk=pk)
        else:
            return HttpResponseForbidden()
    else:
        if request.user.is_anonymous():
            return HttpResponseForbidden()
        schedule = get_object_or_404(Schedule, pk=pk, user=user)

    # Create the HttpResponse object with the appropriate PDF headers.
    # and use it to the create the PDF using it as a file like object
    response = HttpResponse(content_type='application/pdf')
    doc = SimpleDocTemplate(response,
                            pagesize=A4,
                            leftMargin=cm,
                            rightMargin=cm,
                            topMargin=0.5 * cm,
                            bottomMargin=0.5 * cm,
                            title=_('Workout'),
                            author='wger Workout Manager',
                            subject='Schedule for {0}'.format(
                                request.user.username))

    # container for the 'Flowable' objects
    elements = []

    # Set the title
    p = Paragraph(u'<para align="center">{0}</para>'.format(schedule),
                  styleSheet["HeaderBold"])
    elements.append(p)
    elements.append(Spacer(10 * cm, 0.5 * cm))

    # Iterate through the Workout and render the training days
    for step in schedule.schedulestep_set.all():
        p = Paragraph(
            u'<para>{0} {1}</para>'.format(step.duration, _('Weeks')),
            styleSheet["HeaderBold"])
        elements.append(p)
        elements.append(Spacer(10 * cm, 0.5 * cm))

        for day in step.workout.canonical_representation['day_list']:
            elements.append(
                render_workout_day(day,
                                   images=images,
                                   comments=comments,
                                   nr_of_weeks=7))
            elements.append(Spacer(10 * cm, 0.5 * cm))

    # Footer, date and info
    elements.append(Spacer(10 * cm, 0.5 * cm))
    url = reverse('manager:schedule:view', kwargs={'pk': schedule.id})
    elements.append(render_footer(request.build_absolute_uri(url)))

    # write the document and send the response to the browser
    doc.build(elements)
    response[
        'Content-Disposition'] = 'attachment; filename=Schedule-{0}-log.pdf'.format(
            pk)
    response['Content-Length'] = len(response.content)
    return response
Beispiel #28
0
def export_pdf(request, id, uidb64=None, token=None):
    '''
    Generates a PDF with the contents of a nutrition plan

    See also
    * http://www.blog.pythonlibrary.org/2010/09/21/reportlab
    * http://www.reportlab.com/apis/reportlab/dev/platypus.html
    '''

    # Load the plan
    if uidb64 is not None and token is not None:
        if check_token(uidb64, token):
            plan = get_object_or_404(NutritionPlan, pk=id)
        else:
            return HttpResponseForbidden()
    else:
        if request.user.is_anonymous():
            return HttpResponseForbidden()
        plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)

    plan_data = plan.get_nutritional_values()

    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')

    # Create the PDF object, using the response object as its "file."
    doc = SimpleDocTemplate(response,
                            pagesize=A4,
                            title=_('Nutrition plan'),
                            author='wger Workout Manager',
                            subject=_('Nutritional plan %s') % request.user.username)

    # Background colour for header
    # Reportlab doesn't use the HTML hexadecimal format, but has a range of
    # 0 till 1, so we have to convert here.
    header_colour = colors.Color(int('73', 16) / 255.0,
                                 int('8a', 16) / 255.0,
                                 int('5f', 16) / 255.0)

    # container for the 'Flowable' objects
    elements = []
    data = []

    # Iterate through the Plan
    meal_markers = []
    ingredient_markers = []

    # Meals
    i = 0
    for meal in plan.meal_set.select_related():
        i += 1

        meal_markers.append(len(data))

        if not meal.time:
            p = Paragraph(u'<para align="center"><strong>{nr} {meal_nr}</strong></para>'
                          .format(nr=_('Nr.'), meal_nr=i),
                          styleSheet["Normal"])
        else:
            p = Paragraph(u'<para align="center"><strong>'
                          u'{nr} {meal_nr} - {meal_time}'
                          u'</strong></para>'
                          .format(nr=_('Nr.'), meal_nr=i, meal_time=meal.time.strftime("%H:%M")),
                          styleSheet["Normal"])
        data.append([p])

        # Ingredients
        for item in meal.mealitem_set.select_related():
            ingredient_markers.append(len(data))

            p = Paragraph(u'<para>{0}</para>'.format(item.ingredient.name), styleSheet["Normal"])
            if item.get_unit_type() == MEALITEM_WEIGHT_GRAM:
                unit_name = 'g'
            else:
                unit_name = ' ' + item.weight_unit.unit.name

            data.append([Paragraph(u"{0}{1}".format(item.amount, unit_name), styleSheet["Normal"]),
                         p])

    # Set general table styles
    table_style = []

    # Set specific styles, e.g. background for title cells
    for marker in meal_markers:
        # Set background colour for headings
        table_style.append(('BACKGROUND', (0, marker), (-1, marker), header_colour))
        table_style.append(('BOX', (0, marker), (-1, marker), 1.25, colors.black))

        # Make the headings span the whole width
        table_style.append(('SPAN', (0, marker), (-1, marker)))

    # has the plan any data?
    if data:
        t = Table(data, style=table_style)

        # Manually set the width of the columns
        t._argW[0] = 2.5 * cm

    # There is nothing to output
    else:
        t = Paragraph(_('<i>This is an empty plan, what did you expect on the PDF?</i>'),
                      styleSheet["Normal"])

    # Set the title (if available)
    if plan.description:
        p = Paragraph('<para align="center"><strong>%(description)s</strong></para>' %
                      {'description': plan.description},
                      styleSheet["Bold"])
        elements.append(p)

        # Filler
        elements.append(Spacer(10 * cm, 0.5 * cm))

    # append the table to the document
    elements.append(t)
    elements.append(Paragraph('<para>&nbsp;</para>', styleSheet["Normal"]))

    # Create table with nutritional calculations
    data = []
    data.append([Paragraph(u'<para align="center">{0}</para>'.format(_('Nutritional data')),
                 styleSheet["Bold"])])
    data.append([Paragraph(_('Macronutrients'), styleSheet["Normal"]),
                 Paragraph(_('Total'), styleSheet["Normal"]),
                 Paragraph(_('Percent of energy'), styleSheet["Normal"]),
                 Paragraph(_('g per body kg'), styleSheet["Normal"])])
    data.append([Paragraph(_('Energy'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['energy']), styleSheet["Normal"])])
    data.append([Paragraph(_('Protein'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['protein']), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['percent']['protein']), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['per_kg']['protein']), styleSheet["Normal"])])
    data.append([Paragraph(_('Carbohydrates'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['carbohydrates']),
                           styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['percent']['carbohydrates']),
                           styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['per_kg']['carbohydrates']),
                           styleSheet["Normal"])])
    data.append([Paragraph(_('Sugar content in carbohydrates'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['carbohydrates_sugar']),
                           styleSheet["Normal"])])
    data.append([Paragraph(_('Fat'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['fat']), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['percent']['fat']), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['per_kg']['fat']), styleSheet["Normal"])])
    data.append([Paragraph(_('Saturated fat content in fats'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['fat_saturated']),
                           styleSheet["Normal"])])
    data.append([Paragraph(_('Fibres'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['fibres']), styleSheet["Normal"])])
    data.append([Paragraph(_('Sodium'), styleSheet["Normal"]),
                 Paragraph(six.text_type(plan_data['total']['sodium']), styleSheet["Normal"])])

    table_style = []
    table_style.append(('BOX', (0, 0), (-1, -1), 1.25, colors.black))
    table_style.append(('GRID', (0, 0), (-1, -1), 0.40, colors.black))
    table_style.append(('SPAN', (0, 0), (-1, 0)))  # Title
    table_style.append(('SPAN', (1, 2), (-1, 2)))  # Energy
    table_style.append(('SPAN', (1, 5), (-1, 5)))  # Sugar
    table_style.append(('SPAN', (1, 7), (-1, 7)))  # Saturated fats
    table_style.append(('SPAN', (1, 8), (-1, 8)))  # Fibres
    table_style.append(('SPAN', (1, 9), (-1, 9)))  # Sodium
    t = Table(data, style=table_style)
    t._argW[0] = 5 * cm
    elements.append(t)

    # Footer, date and info
    elements.append(Spacer(10 * cm, 0.5 * cm))
    created = datetime.date.today().strftime("%d.%m.%Y")
    url = reverse('nutrition:plan:view', kwargs={'id': plan.id})
    p = Paragraph('''<para align="left">
                        %(date)s -
                        <a href="%(url)s">%(url)s</a> -
                        %(created)s
                        %(version)s
                    </para>''' %
                  {'date': _("Created on the <b>%s</b>") % created,
                   'created': "wger Workout Manager",
                   'version': get_version(),
                   'url': request.build_absolute_uri(url), },
                  styleSheet["Normal"])
    elements.append(p)
    doc.build(elements)

    response['Content-Disposition'] = 'attachment; filename=nutritional-plan.pdf'
    response['Content-Length'] = len(response.content)
    return response
Beispiel #29
0
    def get(self, request, *args, **kwargs):
        response = HttpResponse(content_type='application/pdf')
        buff = BytesIO()
        doc = SimpleDocTemplate(buff,
                                pagesize=letter,
                                rightMargin=40,
                                leftMargin=40,
                                topMargin=60,
                                bottomMargin=30,
                                title='REFERENCIA OXXO')
        items = []

        stylo_p_center = ParagraphStyle('parrafo_center',
                                        alignment=TA_CENTER,
                                        fontSize=11,
                                        fontName="Times-Roman")
        stylo_p_derecha = ParagraphStyle('parrafo_center',
                                         alignment=TA_RIGHT,
                                         fontSize=11,
                                         fontName="Times-Roman")
        stylo_p_izquierda = ParagraphStyle('parrafo_center',
                                           alignment=TA_LEFT,
                                           fontSize=12,
                                           fontName="Times-Roman")
        stylo_p_center_INFO = ParagraphStyle('parrafo_center',
                                             alignment=TA_CENTER,
                                             fontSize=8,
                                             fontName="Times-Roman")
        stylo_p = ParagraphStyle('parrafo',
                                 alignment=TA_LEFT,
                                 fontSize=18,
                                 fontName="Times-Roman")
        stylo_titulo = ParagraphStyle('titulo',
                                      alignment=TA_CENTER,
                                      fontSize=14,
                                      fontName="Times-Bold")
        stylo_titulo_normal = ParagraphStyle('titulo',
                                             alignment=TA_CENTER,
                                             fontSize=14,
                                             fontName="Times-Roman")
        stylo_portada_title = ParagraphStyle('titulo',
                                             alignment=TA_CENTER,
                                             fontSize=20,
                                             fontName="Times-Bold")

        ord_object = Orden.objects.get(ord_order_id=self.kwargs['ord'])

        dta = []

        items.append(
            Image(os.path.realpath('static/img/oxxopay1.jpg'), 8 * cm, 5 * cm))
        text = """MONTO A PAGAR"""
        items.append(Paragraph(text, stylo_titulo))
        items.append(Spacer(0, 10))

        text = """${} MXN""".format(intcomma(ord_object.ord_monto))
        items.append(Paragraph(text, stylo_titulo_normal))
        items.append(Spacer(0, 10))

        text = """OXXO Cobra una comision al momento de realizar el pago"""
        items.append(Paragraph(text, stylo_titulo_normal))
        items.append(Spacer(0, 20))

        text = """REFERENCIA"""
        items.append(Paragraph(text, stylo_p))
        items.append(Spacer(0, 20))

        text = """{}""".format(ord_object.ord_referencia)
        items.append(Paragraph(text, stylo_portada_title))
        items.append(Spacer(0, 15))
        items.append(Image(ord_object.ord_barcode_url, 5 * cm, 1.5 * cm))
        items.append(Spacer(0, 30))

        text = """INSTRUCCIONES"""
        items.append(Paragraph(text, stylo_titulo))
        items.append(Spacer(0, 20))

        text = """1. Acude a la tienda OXXO más cercana."""
        items.append(Paragraph(text, stylo_p_izquierda))
        items.append(Spacer(0, 10))

        text = """2. Indica en caja que quieres realizar un pago de OXXOPay"""
        items.append(Paragraph(text, stylo_p_izquierda))
        items.append(Spacer(0, 10))

        text = """3. Dicta al cajero el número de referencia en esta ficha para que tecleé directamente en la pantalla de venta."""
        items.append(Paragraph(text, stylo_p_izquierda))
        items.append(Spacer(0, 10))

        text = """4. Realiza el pago correspondiente con dinero en efectivo."""
        items.append(Paragraph(text, stylo_p_izquierda))
        items.append(Spacer(0, 10))

        text = """5. Al confirmar tu pago, el cajero te entregará un comprobante impreso. En el podrás verificar que se haya realizado correctamente.Conserve este comprobante de pago."""
        items.append(Paragraph(text, stylo_p_izquierda))
        items.append(Spacer(0, 10))

        # data_table = [(
        #     Image(os.path.realpath('static/img/OXXO.png'), 5*cm, 5*cm),
        #     Paragraph(text, stylo_p),
        #     )]

        # tabla = Table(data_table, colWidths=[
        #     15 * cm,
        #     5 * cm,
        #     ])

        # tabla.setStyle(TableStyle(
        #     [
        #         ('GRID', (0, 0), (-1, -1), 1, colors.black),
        #         # ('LINEBELOW', (0, 0), (-1, 0), 0, colors.darkblue),
        #         ('BACKGROUND', (0, 0), (-1, 0), colors.transparent)
        #     ]
        # ))

        # items.append(tabla)

        # items.append(Paragraph("FICHA DIGITAL NOES NECESARIO IMPRIMIR", stylo_titulo))

        # items.append(Spacer(0, 20))

        doc.build(items,
                  onFirstPage=self.myFirstPage,
                  onLaterPages=self.myLaterPages)
        response.write(buff.getvalue())
        buff.close()
        return response
Beispiel #30
0
def generate_donation_receipt(member, year):
    fees = member.fee_payments.filter(value_datetime__year=year).aggregate(
        fees=models.Sum('amount'))['fees'] or Decimal('0.00')
    donations = member.donations.filter(value_datetime__year=year).aggregate(
        donations=models.Sum('amount'))['donations'] or Decimal('0.00')
    address = member.address
    if (donations + fees) <= 0:
        raise Exception(f'No donations or fees for {year}.')

    story = []
    _buffer = BytesIO()
    local_settings = GemeinnuetzigkeitConfiguration.get_solo()
    global_settings = Configuration.get_solo()
    doc = get_default_document(_buffer)
    style = get_paragraph_style()

    # Header
    our_address = '\n'.join([global_settings.name,
                             global_settings.address]).replace('\n', '<br />')
    our_address = Paragraph(our_address, style['Normal'])
    our_title = Paragraph('Aussteller (Steuerbegünstigte Einrichtung)',
                          style['Heading5'])
    story.append(
        Table(
            [[
                our_title,
            ], [
                our_address,
            ]],
            colWidths=[doc.width * 1],
            hAlign='LEFT',
            style=TableStyle([
                ('ALIGN', (0, 0), (0, 0), 'CENTER'),
                ('BOX', (0, 0), (0, 1), 0.5, colors.black),
            ]),
        ))
    story.append(
        Paragraph('Bestätigung über Geldzuwendungen/Mitgliedsbeitrag',
                  style['Heading3']))
    story.append(
        Paragraph(
            'im Sinne des § 10b des Einkommenssteuergesetzes an eine der in § 5 Abs. 1 Nr. 9 des Körperschaftssteuergesetzes bezeichneten Körperschaften, Personenvereinigungen oder Vermögensmassen',
            style['Normal']))
    story.append(Spacer(1, 5 * mm))

    their_address = address.replace('\n', '<br />')
    their_address = Paragraph(their_address, style['Normal'])
    their_title = Paragraph('Name und Anschrift des Zuwendenden',
                            style['Heading5'])
    story.append(
        Table(
            [[their_title], [their_address]],
            colWidths=[doc.width * 1],
            style=TableStyle([
                ('ALIGN', (0, 0), (0, 0), 'CENTER'),
                ('BOX', (0, 0), (0, 1), 0.5, colors.black),
            ]),
        ))
    story.append(Spacer(1, 5 * mm))

    data = [
        [_('Product'), _('Tax rate'),
         _('Net'), _('Gross')],
    ]
    data = [['Art', 'in Ziffern', 'in Buchstaben', 'Datum']]
    if fees:
        data.append([
            'Beiträge',
            CURRENCY.format(fees),
            lib_num2words(fees, lang='de'), year
        ])
    if donations:
        data.append([
            'Spenden',
            CURRENCY.format(donations),
            lib_num2words(donations, lang='de'), year
        ])
    last_row = len(data) - 1

    story.append(
        Table(
            data=data,
            colWidths=[
                doc.width * 0.15, doc.width * 0.15, doc.width * 0.5,
                doc.width * 0.2
            ],
            style=TableStyle([
                ('FONTSIZE', (0, 0), (3, last_row), FONTSIZE),
                ('ALIGN', (0, 0), (1, last_row), 'LEFT'),
                ('ALIGN', (3, 0), (3, last_row), 'RIGHT'),
                ('BOX', (0, 0), (3, last_row), 1.0, colors.black),
                ('GRID', (0, 0), (3, last_row), 0.5, colors.black),
            ]),
        ))
    story.append(Spacer(1, 5 * mm))

    story.append(
        Paragraph(
            'Es handelt sich NICHT um den Verzicht auf Erstattung von Aufwendungen.',
            style['Normal']))
    story.append(Spacer(1, 5 * mm))
    loong = 'Wir sind wegen Förderung {zwecke} nach dem Freistellungsbescheid bzw. nach der Anlage zum Körperschaftssteuerbescheid des Finanzamts {amt} StNr. {nummer} vom {datum} für den letzten Veranlagungszeitraum {zeitraum} nach § 5 Abs. 1 Nr. 9 des Körperschaftssteuergesetzes von der Körperschaftssteuer und nach § 3 Nr. 6 des Gewerbesteuergesetzes von der Gewerbesteuer befreit.'
    loong = loong.format(
        zwecke=local_settings.reason,
        amt=local_settings.finanzamt,
        nummer=local_settings.vat_id,
        datum=local_settings.notification_date,
        zeitraum=local_settings.veranlagungszeitraum,
    )
    story.append(Paragraph(loong, style['Normal']))
    story.append(Spacer(1, 5 * mm))
    story.append(
        Table(
            [[
                Paragraph(
                    'Es wird bestätigt, dass die Zuwendung nur zur Förderung {zwecke} verwendet wird.'
                    .format(zwecke=local_settings.reason), style['Normal'])
            ]],
            colWidths=[doc.width * 1],
            style=TableStyle([
                ('ALIGN', (0, 0), (0, 0), 'CENTER'),
                ('BOX', (0, 0), (0, 0), 0.5, colors.black),
            ]),
        ))

    story.append(Spacer(1, 25 * mm))
    data = [[
        '{location}, {date}'.format(location=local_settings.location,
                                    date=now().date().isoformat())
    ], ['(Ort, Datum, und Unterschrift des Zuwendungsempfängers)']]
    story.append(
        Table(
            data=data,
            colWidths=[doc.width],
            style=TableStyle([
                ('LINEABOVE', (0, 1), (0, 1), 1.0, colors.black),
            ]),
        ))

    story.append(Spacer(1, 5 * mm))
    disclaimer1 = 'Wer vorsätzlich oder grob fahrlässig eine unrichtige Zuwendungsbestätigung erstellt oder wer veranlasst, dass Zuwendungen nicht zu den in der Zuwendungsbestätigung angegebenen steuerbegünstigten Zwecken verwendet werden, haftet für die Steuer, die dem Fiskus durch einen etwaigen Abzug der Zuwendungen beim Zuwendenden entgeht (§10b Abs. 4 EStG, §9 Abs. 3 KStG, §9 Nr. 5 GewStG).'
    disclaimer2 = 'Diese Bestätigung wird nicht als Nachweis für die steuerliche Berücksichtigung der Zuwendung anerkannt, wenn das Datum des Freistellungsbescheides länger als 5 Jahre bzw. das Datum der vorläufigen Bescheinigung länger als 3 Jahre seit Ausstellung der Bestätigung zurückliegt (BMF vom 15.12.1994 – BStBl I S. 884).'
    story.append(Paragraph('Hinweis', style['Heading5']))
    story.append(Paragraph(disclaimer1, style['Normal']))
    story.append(Paragraph(disclaimer2, style['Normal']))

    doc.build(story)
    _buffer.seek(0)
    doc = Document.objects.create(
        title='Zuwendungsbestätigung {}'.format(year),
        category=DOCUMENT_CATEGORY,
        member=member,
    )
    doc.document.save(
        'spenden/spenden_{}_{}_{}.pdf'.format(year, member.number,
                                              member.name),
        ContentFile(_buffer.read()))
    doc.save()
    return doc.document.url
    def __init__(self,
                 dictDonnees={},
                 nomDoc=FonctionsPerso.GenerationNomDoc(
                     "RECUDONAUXOEUVRES", "pdf"),
                 afficherDoc=True):
        """ Imprime un reçu Dons aux Oeuvres """

        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
        from reportlab.rl_config import defaultPageSize
        from reportlab.lib.units import inch, cm
        from reportlab.lib import colors
        from reportlab.lib.styles import getSampleStyleSheet
        styleSheet = getSampleStyleSheet()
        self.hauteur_page = defaultPageSize[1]
        self.largeur_page = defaultPageSize[0]
        self.inch = inch

        # Initialisation du PDF
        PAGE_HEIGHT = defaultPageSize[1]
        PAGE_WIDTH = defaultPageSize[0]
        doc = SimpleDocTemplate(nomDoc)
        story = []

        # ---------------- Titre du document ----------------------------------------------------------------

        largeursColonnes = ((300, 150))

        txt1 = Paragraph(
            u"""
        <para align=center fontSize=16><b>Reçu Dons Aux Oeuvres</b></para>
        """, styleSheet['BodyText'])

        txt2 = Paragraph(
            u"""
        <para align=center fontSize=8>Numéro d'ordre du reçu</para>
        """, styleSheet['BodyText'])

        txt3 = Paragraph(
            u"""
        <para align=center fontSize=9>(Article 200-5 du Code Général des Impôts)</para>
        """, styleSheet['BodyText'])

        txt4 = Paragraph(
            u"""
        <para align=center fontsize=16>%s</para>
        """ % dictDonnees["numero"], styleSheet['BodyText'])

        # Valeurs du tableau
        dataTableau = [
            ["", txt2],
            [[txt1, txt3], txt4],
        ]

        # Style du tableau
        style = TableStyle([
            ('GRID', (1, 1), (1, 1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), "MIDDLE"),
        ])
        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(style)
        story.append(tableau)
        story.append(Spacer(0, 20))

        # ------------ Corps du document -----------------------------------------------------
        largeursColonnes = ((450, ))

        # Texte du tableau
        txt10 = Paragraph(
            u"""
        <para align=center><b>Bénéficiaire des versements</b></para>
        """, styleSheet['BodyText'])

        txt20 = Paragraph(
            u"""
        <br/>
        Nom ou dénomination : %s<br/>
        <br/>
        Adresse : %s<br/>
        <br/>
        Objet : %s<br/>
        <br/>
        %s<br/>   
        <br/>     
        """ % (dictDonnees["nom_organisme"], dictDonnees["adresse_organisme"],
               dictDonnees["objet_organisme"], dictDonnees["type_organisme"]),
            styleSheet['BodyText'])

        # Donateur
        txt30 = Paragraph(
            u"""
        <para align=center><b>Donateur</b></para>
        """, styleSheet['BodyText'])

        txt40 = Paragraph(
            u"""
        <br/>
        Nom : %s<br/>
        <br/>
        Adresse : %s
        <br/>
        <br/>
        """ % (dictDonnees["nom_donateur"], dictDonnees["adresse_donateur"]),
            styleSheet['BodyText'])

        # Montant
        txt50 = Paragraph(
            u"""
        <para align=center><b>Versement</b></para>
        """, styleSheet['BodyText'])

        txt60 = Paragraph(
            u"""
        <br/>
        Le bénéficiaire reconnaît avoir reçu au titre des versements ouvrant droit à réduction d'impôt la somme de : <br/>
        <br/>
        """, styleSheet['BodyText'])

        txt70 = Paragraph(
            u"""
        <para align=center fontSize=12>
        <b>%s</b><br/>
        <br/>
        <b>Soit %s</b>
        </para>
        """ %
            (dictDonnees["montant_chiffres"], dictDonnees["montant_lettres"]),
            styleSheet['BodyText'])

        txt80 = Paragraph(
            u"""
        <br/>
        Date du paiement : %s<br/>
        <br/>
        Mode de versement : %s
        <br/>
        <br/>
        """ % (dictDonnees["date_versement"], dictDonnees["mode"]),
            styleSheet['BodyText'])

        txt100 = Paragraph(
            u"""
        Fait en double exemplaire<br/>
        (Un pour le donateur - un pour l'association)<br/>
        <br/>
        """, styleSheet['BodyText'])

        if dictDonnees["date_edition"] != u"":
            date_edition = _(u"Le %s") % dictDonnees["date_edition"]
        else:
            dictDonnees["date_edition"] = u""

        txt110 = Paragraph(
            u"""
        <para align=right rightIndent=50>
        Date et signature
        <br/>
        <br/>
        %s
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        </para>
        """ % date_edition, styleSheet['BodyText'])

        # Valeurs du tableau
        dataTableau = [
            [
                txt10,
            ],
            [
                txt20,
            ],
            [
                "",
            ],
            [
                txt30,
            ],
            [
                txt40,
            ],
            [
                "",
            ],
            [
                txt50,
            ],
            [
                [txt60, txt70, txt80, txt100, txt110],
            ],
        ]

        # Style du tableau
        style = TableStyle([
            ('GRID', (0, 0), (0, 1), 0.25, colors.black),
            ('GRID', (0, 3), (0, 4), 0.25, colors.black),
            ('GRID', (0, 6), (0, 7), 0.25, colors.black),
        ])
        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(style)
        story.append(tableau)
        story.append(Spacer(0, 20))

        # Enregistrement du PDF
        try:
            doc.build(story)
        except Exception, err:
            print "Erreur dans ouverture PDF :", err
            if "Permission denied" in err:
                dlg = wx.MessageDialog(
                    None,
                    _(u"Noethys ne peut pas créer le PDF.\n\nVeuillez vérifier qu'un autre PDF n'est pas déjà ouvert en arrière-plan..."
                      ), _(u"Erreur d'édition"), wx.OK | wx.ICON_ERROR)
                dlg.ShowModal()
                dlg.Destroy()
                return
Beispiel #32
0
def some_view3(request, *args, **kwargs):

    from django.http import HttpResponse

    from reportlab.lib import colors
    from reportlab.lib.pagesizes import letter, inch
    from reportlab.platypus import Image, Paragraph, SimpleDocTemplate, Table, TableStyle, Frame, PageTemplate, BaseDocTemplate, FrameBreak, Spacer
    from reportlab.lib.styles import getSampleStyleSheet


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

    #A4 width = 8.5 inches

    # define frames - for frames in page
    # frameHeader = Frame(x1=0*inch, y1=10.0*inch, width=8.5*inch, height=1.0*inch, showBoundary=1)


    # frameTable1 = Frame(x1=0.0*inch, y1=6.25*inch, width=3.8*inch, height=3.95*inch, showBoundary=1)
    # frameTable2 = Frame(x1=3.8*inch, y1=6.25*inch, width=4.7*inch, height=3.95*inch, showBoundary=1)

    # #Articles
    # frameTable3 = Frame(x1=0*inch, y1=2.0*inch, width=8.5*inch, height=4.25*inch, showBoundary=1)

    # frameTable4 = Frame(x1=0.0*inch, y1=0.7*inch, width=4.25*inch, height=1.3*inch, showBoundary=1)
    # frameTable5 = Frame(x1=4.25*inch, y1=0.7*inch, width=4.25*inch, height=1.3*inch, showBoundary=1)


    # frameTable6 = Frame(x1=0.4*inch, y1=0.0*inch, width=1.6*inch, height=0.7*inch, showBoundary=1)
    # frameTable7 = Frame(x1=2.0*inch, y1=0.0*inch, width=1.5*inch, height=0.7*inch, showBoundary=1)   
    # frameTable8 = Frame(x1=3.5*inch, y1=0.0*inch, width=1.5*inch, height=0.7*inch, showBoundary=1)
    # frameTable9 = Frame(x1=5.0*inch, y1=0.0*inch, width=1.5*inch, height=0.7*inch, showBoundary=1)   
    # frameTable10 = Frame(x1=6.5*inch, y1=0.0*inch, width=1.6*inch, height=0.7*inch, showBoundary=1)


    frameHeader = Frame(x1=0*inch, y1=10.0*inch, width=8.5*inch, height=1.0*inch,)


    frameTable1 = Frame(x1=0.0*inch, y1=6.25*inch, width=3.8*inch, height=3.95*inch)
    frameTable2 = Frame(x1=3.8*inch, y1=6.25*inch, width=4.7*inch, height=3.95*inch)

    #Articles
    frameTable3 = Frame(x1=0*inch, y1=2.0*inch, width=8.5*inch, height=4.50*inch)

    frameTable4 = Frame(x1=0.2*inch, y1=0.7*inch, width=4.25*inch, height=1.3*inch)
    frameTable5 = Frame(x1=4.48*inch, y1=0.7*inch, width=4.25*inch, height=1.3*inch)


    frameTable6 = Frame(x1=0.4*inch, y1=0.0*inch, width=1.6*inch, height=0.7*inch)
    frameTable7 = Frame(x1=2.0*inch, y1=0.0*inch, width=1.5*inch, height=0.7*inch)   
    frameTable8 = Frame(x1=3.5*inch, y1=0.0*inch, width=1.5*inch, height=0.7*inch)
    frameTable9 = Frame(x1=5.0*inch, y1=0.0*inch, width=1.5*inch, height=0.7*inch)   
    frameTable10 = Frame(x1=6.5*inch, y1=0.0*inch, width=1.6*inch, height=0.7*inch)

    #frameTable6 = Frame(x1=5.5625*inch, y1=7.0*inch, width=1.5*inch, height=1.0*inch)
    #Checkboxes
    #frameTable7 = Frame(x1=1.0625*inch, y1=1.5*inch, width=1.5*inch, height=6.2*inch)
    #frameTable8 = Frame(x1=2.5625*inch, y1=1.5*inch, width=5.5*inch, height=5.5*inch)
    #Signature
    #frameTable9 = Frame(x1=0*inch, y1=0.5*inch, width=8.5*inch, height=1.0*inch)


    # define pageTemplates - for page in document
    mainPage = PageTemplate(frames=[frameHeader, frameTable1, frameTable2,
                                    frameTable3, frameTable4, frameTable5,
                                    frameTable6, frameTable7, frameTable8,
                                    frameTable9, frameTable10
    ])

    # define BasicDocTemplate - for document
    doc = BaseDocTemplate(response, pagesize=letter, pageTemplates=mainPage)
    
    # styles
    styleSheet = getSampleStyleSheet()
    styleH = styleSheet['Heading1']

    # create a story
    # container for the 'Flowable' objects
    elements = []
    


    # Add all the flowables to different frames
    #elements.append(heading)
    #elements.append(FrameBreak())      # move to next frame   


    #TESTING FRAMES
    #Two Columns
    #frame1 = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height, id='col1', showBoundary=1)
    #frame2 = Frame(doc.leftMargin+doc.width/2+6, doc.bottomMargin, doc.width/2-6, doc.height, id='col2', showBoundary=1)
    #doc.addPageTemplates([PageTemplate(id='TwoCol',frames=[frame1,frame2]), ])

    #I = Image('replogo.gif')
    #I.drawHeight = 1.25*inch*I.drawHeight / I.drawWidth
    #I.drawWidth = 1.25*inch


    ###############################################################
    #Hamta modeller som kommer anvandas fran databasen

    workorder = Workorder.objects.get(pk=kwargs.get('pk', None))

    #Serviceprotocol.objects.get(pk=kwargs.get('pk', None))
    #print(Serviceprotocol) 
    #  for product in Product.objects.all():
    #   p = Paragraph("%s" % product.name, style)
    #   Catalog.append(p)
    #   s = Spacer(1, 0.25*inch)
    #   Catalog.append(s)
    # doc.build(Catalog) 


    ###############################################################

    ###############################################################
    #Rubrik

    h = Paragraph("""<para align=center spaceb=3><b>Arbetsorder</b></para>""", styleH)
     
    elements.append(h)

    g = Spacer(1, 0.05*inch)

    elements.append(g)

    ###############################################################

    ###############################################################
    #DATUM
    data = [['Datum:', workorder.date]]
    a=Table(data,style=[
                        #('BOX',(0,0),(-1,-1),2,colors.black),
                        ('LINEBELOW',(0,0),(1,0),1,colors.black),
                        ('ALIGN',(0,0),(0,0),'CENTER'),
                        ('ALIGN',(0,0),(-1,-1),'LEFT'),
                        
    ])
    a._argW[-1]=1.1*inch
     
    elements.append(a)
    elements.append(FrameBreak())

    ###############################################################

    ###############################################################
    #Company information

    data = [["Nilsson's MC Shop AB"],
            ['Industrigatan 48'],
            ['58277 Linköping'],
            ['Tel 013-141459'],
            ['Verkstad Mob. 072-7141471'],
            ['ESD 2012']]

    b=Table(data,style=[        #(col, row)
                        ('ALIGN',(0,0),(0,5),'CENTER'),
                        
    ])
    #f._argW[0]=1.6*inch
    
    
    elements.append(b)
    elements.append(FrameBreak())
    ###############################################################

    ###############################################################
    #Customer and motorcykle information
    #foo = 'Blablabla bla bla blall bllalall bla bla blall bllalall bla bal Blablabla bla bla blall bllalall bla bal Blablabla bla bla blall bllalall bla bal Blablabla bla bla blall bllalall bla bal bla bal bla b !MAX 4 RADER!'
    #bar = 'Foo Bar foobar foobar fo bar fofofo bar Foo Bar foobar foobar fo bar fofofo bar Foo Bar foobar foobar fo bar fofofo bar Foo Bar foobar foobar fo bar fofofo bar fo bar fofofo bar !MAX 4 RADER!'



    p1 = Paragraph("%s" % workorder.job, styleSheet["BodyText"])
    p2 = Paragraph("%s" % workorder.notification, styleSheet["BodyText"])

    data = [['Kund:', workorder.customer.first_name + " " + workorder.customer.last_name],
            ['Adress:', workorder.customer.street],
            ['Telefon:', workorder.customer.telephone_set.all()[0]],
            ['Mc:', workorder.brand],
            ['Modell:', workorder.model],
            ['År:', workorder.year],
            ['Motor:', workorder.motor],
            ['Arbete:', p1],
            ['Anm:', p2],
            ['Regnr:', workorder.registration_nr],
            ['Km:', workorder.km]]

    c=Table(data,style=[        #(col, row)
                        #('GRID',(0,0),(-1,-1),2,colors.black),
                        #('LINEABOVE',(1,1),(1,1),1,colors.black),
                        #('LINEABOVE',(1,2),(1,2),1,colors.black),
                        #('LINEABOVE',(1,3),(1,3),1,colors.black),
                        #('LINEABOVE',(1,4),(1,4),1,colors.black),
                        ('VALIGN',(0,7),(0,8),'TOP'),
                        ('ALIGN',(0,0),(-1,-1),'LEFT'),
                        
    ])
    c._argW[1]=3.7*inch

    elements.append(c)

    elements.append(FrameBreak())
    ###############################################################

    ###############################################################
    #Articles

    data = [['Art.nr.', 'Antal', 'Benämning', 'Pris st', 'Pris']]

    d=Table(data,style=[        #(col, row)
                        ('GRID',(0,1),(-1,-1),2,colors.black),
                        ('ALIGN',(0,0),(-1,-1),'LEFT'),             
    ])
    d._argW[0]=1.0*inch
    d._argW[1]=1.0*inch
    d._argW[2]=3.0*inch
    d._argW[3]=1.0*inch
    d._argW[4]=1.0*inch

    elements.append(d)


    #For varje artikel lagg till rad med information
    #MAX 15 articles

    existing_articles = int(workorder.article_set.all().count())
    max_articles = 15
    #Check if workorder has any articles
     
    #counter = 0
    for article in workorder.article_set.all():
        #counter += 1
        data = [[article.article_nr, article.quantity, article.description, article.price, article.price_total ]]
        e=Table(data,style=[        #(col, row)
                            ('GRID',(0,0),(-1,-1),2,colors.black),
                            ('ALIGN',(0,0),(-1,-1),'LEFT'),             
        ])
        e._argW[0]=1.0*inch
        e._argW[1]=1.0*inch
        e._argW[2]=3.0*inch
        e._argW[3]=1.0*inch
        e._argW[4]=1.0*inch

        elements.append(e)

    #Calculate how many empty rows to fill up
    rest = (max_articles - existing_articles)
    for empty_articles in range(rest):
        data = [['', '', '', '', '']]
        e=Table(data,style=[        #(col, row)
                            ('GRID',(0,0),(-1,-1),2,colors.black),
                            ('ALIGN',(0,0),(-1,-1),'LEFT'),             
        ])
        e._argW[0]=1.0*inch
        e._argW[1]=1.0*inch
        e._argW[2]=3.0*inch
        e._argW[3]=1.0*inch
        e._argW[4]=1.0*inch

        elements.append(e)       

    elements.append(FrameBreak())
    ###############################################################

    ###############################################################
    #Anmarkning
    #foo = "asfadf asdasd asd asdas sadsa d s dsd  s d sds ds sdsss sd sds ss sfadf asdasd asd asdas sadsa d s dsd  s d sds ds sdsss sd sds ss sfadf asdasd asd asdas sadsa d s dsd  s d sds ds !MAX 4 RADER!"

    p3 = Paragraph("%s" % workorder.comment, styleSheet["BodyText"])

    data = [['Anmärkning.'],
            [p3]]

    f=Table(data,style=[        #(col, row)
                        #('GRID',(0,1),(-1,-1),2,colors.black),
                        ('ALIGN',(0,0),(-1,-1),'LEFT'),             
    ])
    #f._argW[0]=1.0*inch
    f._argW[0]=3.3*inch

    elements.append(f)

    elements.append(FrameBreak())
    ###############################################################

    ###############################################################
    #Summering

    cal = workorder.workorder_calculations()

    data = [['Fö. Matr..', cal['expendables']],
            ['Summa', cal['sum']],
            ['Moms:', cal['vat']],
            ['Att betala:', cal['total']]]

    g=Table(data,style=[        #(col, row)
                        ('GRID',(1,0),(-1,-1),2,colors.black),
                        ('ALIGN',(0,0),(-1,-1),'LEFT'),
                        
    ])
    g._argW[1]=1.5*inch

    elements.append(g)

    elements.append(FrameBreak())
    ###############################################################

    ###############################################################
    #

    data = [["Orgnnr."],
            ['556877-4938']]

    h=Table(data,style=[        #(col, row)
                        ('ALIGN',(0,0),(-1,-1),'CENTER'),     
    ])
    #f._argW[0]=1.6*inch
    
    
    elements.append(h)
    elements.append(FrameBreak())
    ###############################################################

    ###############################################################
    #
    data = [["Momsregnn/VAT"],
            ['SE5568774938']]

    h=Table(data,style=[        #(col, row)
                        ('ALIGN',(0,0),(-1,-1),'CENTER'),     
    ])
    #f._argW[0]=1.6*inch
    
    
    elements.append(h)
    elements.append(FrameBreak())
    ###############################################################

    ###############################################################
    #
    data = [["Bankgiro"],
            ['830-5682']]

    h=Table(data,style=[        #(col, row)
                        ('ALIGN',(0,0),(-1,-1),'CENTER'),     
    ])
    #f._argW[0]=1.6*inch
    
    
    elements.append(h)
    elements.append(FrameBreak())
    ###############################################################

    ###############################################################
    #
    data = [["Tel.nr"],
            ['013-141458']]

    h=Table(data,style=[        #(col, row)
                        ('ALIGN',(0,0),(-1,-1),'CENTER'),     
    ])
    #f._argW[0]=1.6*inch
    
    
    elements.append(h)
    elements.append(FrameBreak())
    ###############################################################

    ###############################################################
    #
    data = [["Faxnr."],
            ['013-141458']]

    h=Table(data,style=[        #(col, row)
                        ('ALIGN',(0,0),(-1,-1),'CENTER'),     
    ])
    #f._argW[0]=1.6*inch
    
    
    elements.append(h)
    ###############################################################


    # write the document to disk
    doc.build(elements)

    return response