Beispiel #1
0
def print_agenda(request):
    response = HttpResponse(mimetype='application/pdf')
    filename = u'filename=%s.pdf;' % _("Agenda")
    response['Content-Disposition'] = filename.encode('utf-8')
    doc = SimpleDocTemplate(response)
    story = [Spacer(1,3*cm)]

    doc.title = _("Agenda")
    # print item list
    items = children_list(Item.objects.filter(parent=None).order_by('weight'))
    for item in items:
        if item.hidden is False:
            # print all items"
            if item.parents:
                space = ""
                counter = 0
                for p in item.parents:
                    if counter != 0:
                        space += "      "
                    counter += 1
                story.append(Paragraph(space+item.title, stylesheet['Subitem']))
            else:
                story.append(Paragraph(item.title, stylesheet['Item']))

    doc.build(story, onFirstPage=firstPage, onLaterPages=laterPages)
    return response
Beispiel #2
0
    def go(self):
        """Render the PDF foer individual item."""
        doc = SimpleDocTemplate(self.buf,
                                leftMargin=LEFTMARGIN,
                                rightMargin=RIGHTMARGIN)
        doc.title = self.filename
        doc.creator = "Romain Belia."
        doc.author = "Romain Belia."
        doc.subject = "Report created by Romain Belia."
        doc.keywords = ["report", "Romain Belia"]
        story = []
        # First Page

        story.append(self._build_title("The Report"))
        story.append(Spacer(1, 1 * cm))
        story.append(
            self._build_document_title("organization", self.organization))
        story.append(
            self._build_document_title("reported_at", self.reported_at))
        story.append(self._build_document_title("created_at", self.created_at))
        story.append(Spacer(1, 1 * cm))
        story.append(Spacer(1, 1 * cm))
        if not self.inventory:
            story.append(self._build_no_content())
        for x in self.inventory:
            story.append(self._build_document_content(x))
            story.append(Spacer(1, 1 * cm))
        story.append(PageBreak())

        doc.build(story,
                  onFirstPage=self.firstpage,
                  onLaterPages=self.laterpages)
        return
Beispiel #3
0
def print_assignment(request, assignment_id=None):
    response = HttpResponse(mimetype='application/pdf')
    filename = u'filename=%s.pdf;' % _("Elections")
    response['Content-Disposition'] = filename.encode('utf-8')
    doc = SimpleDocTemplate(response)
    doc.title = None
    story = []
    
    if assignment_id is None:  #print all applications
        title = config_get("assignment_pdf_title")
        story.append(Paragraph(title, stylesheet['Heading1']))
        preamble = config_get("assignment_pdf_preamble")
        if preamble:
            story.append(Paragraph("%s" % preamble.replace('\r\n','<br/>'), stylesheet['Paragraph']))
        story.append(Spacer(0,0.75*cm))
        # List of assignments
        for assignment in Assignment.objects.order_by('name'):
            story.append(Paragraph(assignment.name, stylesheet['Heading3']))
        # Assignment details (each assignment on single page)
        for assignment in Assignment.objects.order_by('name'):
            story.append(PageBreak())
            story = get_assignment(assignment, story)
    else:  # print selected assignment
        assignment = Assignment.objects.get(id=assignment_id)
        filename = u'filename=%s-%s.pdf;' % (_("Assignment"), assignment.name.replace(' ','_'))
        response['Content-Disposition'] = filename.encode('utf-8')
        story = get_assignment(assignment, story)

    doc.build(story, onFirstPage=firstPage, onLaterPages=firstPage)
    return response
Beispiel #4
0
def text_to_pdf(content):
    # Create a buffer file, set-up title and file name
    date = datetime.datetime.now()
    my_doc = SimpleDocTemplate("Day-nytimes-" + str(date.strftime("%Y%m%d")) +
                               '.pdf')
    title = 'DAY - nytimes.com ' + date.strftime("%x")
    my_doc.title = title

    # Set the styles for the title and body
    sample_style_sheet = getSampleStyleSheet()
    pdfmetrics.registerFont(
        TTFont('Times_New_Roman',
               get_script_path() + "/font/Times_New_Roman.ttf"))

    title_style = sample_style_sheet['Heading1']
    title_style.fontName = 'Times_New_Roman'
    title_style.fontSize = 24

    body_style = sample_style_sheet['BodyText']
    body_style.fontName = 'Times_New_Roman'
    body_style.fontSize = 12

    # Collect content and write to PDF
    flowables = []
    title_text = Paragraph(title, sample_style_sheet['Heading1'])
    body_text = Paragraph(content, sample_style_sheet['BodyText'])
    flowables += [title_text, body_text]
    my_doc.build(flowables)

    return True
Beispiel #5
0
def get_document(args, rightMargin=2.5*mm, leftMargin = 2.5*mm, topMargin = 2.5*mm, bottomMargin = 2.5*mm):
    save_path = f'{args.title}.pdf'
    doc = SimpleDocTemplate(save_path)
    doc.title = args.title

    doc.rightMargin = rightMargin
    doc.leftMargin = leftMargin
    doc.topMargin = topMargin
    doc.bottomMargin = bottomMargin
    doc.width = A4[0] - (doc.rightMargin + doc.leftMargin)
    doc.height = A4[1] - (doc.topMargin + doc.bottomMargin)

    return doc
Beispiel #6
0
Datei: lucky.py Projekt: kuba/SIS
    def current_week_pdf(self):
        """Lucky numbers for current or next week in pdf format."""
        change_hour = 15
        numbers = LuckyNumber.current_week(change_hour)

        if len(numbers) == 0:
            return redirect(url('lucky_week'))

        # Register fonts
        ubuntu_r = resource_filename(Requirement.parse("SIS"), "resources/Ubuntu-R.ttf")
        ubuntu_b = resource_filename(Requirement.parse("SIS"), "resources/Ubuntu-B.ttf")
        pdfmetrics.registerFont(TTFont('Ubuntu', ubuntu_r))
        pdfmetrics.registerFont(TTFont('Ubuntu Bold', ubuntu_b))

        numbers_pdf = StringIO.StringIO()
        doc = SimpleDocTemplate(numbers_pdf, pagesize=A4, topMargin=A4[1]*0.26)
        doc.author = 'SIS'
        doc.title = 'Szczęśliwy numerek'

        data = []
        for number in numbers:
            date = number.date.strftime("%d.%m.%y")
            data.append(('{0} -'.format(date), str(number.number)))

        table = Table(data)
        table.setStyle(TableStyle([
            ('FONT', (0, 0), (0, -1), 'Ubuntu', 80),
            ('FONT', (1, 0), (1, -1), 'Ubuntu Bold', 80),
        ]))

        def header_and_footer(canvas, document):
            canvas.saveState()
            size = document.pagesize
            center = size[0] / 2

            canvas.setFont('Ubuntu', 80)
            canvas.drawCentredString(center,
                size[1] - document.topMargin / 2, "SZCZĘŚLIWY")
            canvas.drawCentredString(center, size[1] - document.topMargin + 20, 'NUMEREK')

            canvas.setFont('Ubuntu', 15)
            canvas.drawRightString(size[0] - document.rightMargin,
                document.bottomMargin - 20, "Samorząd Uczniowski")

            canvas.restoreState()

        doc.build([table], onFirstPage=header_and_footer,
            onLaterPages=header_and_footer)

        response.headers['Content-type'] = 'application/pdf'
        return numbers_pdf.getvalue()
Beispiel #7
0
    def MakeSetupSheet(self, pdf_file_path):
        from reportlab.lib import colors
        from reportlab.lib.pagesizes import A4, mm
        from reportlab.platypus import Image, Paragraph, SimpleDocTemplate, Table
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        from reportlab.lib.enums import TA_CENTER

        doc = SimpleDocTemplate(pdf_file_path, pagesize=A4)
        doc.title = 'Setup Sheet'
        # container for the 'Flowable' objects
        elements = []

        styles = getSampleStyleSheet()

        # strip path from output file
        filename = self.GetOutputFileName()
        filename = filename.replace('\\', '/')
        pos = filename.rfind('/')
        filename = filename[pos + 1:]

        elements.append(
            Paragraph('Setup Sheet for ' + filename, styles['Title']))

        box = wx.GetApp().program.stocks.GetBoxWithInvisibles()

        elements.append(Paragraph('Stock', styles['Heading2']))
        elements.append(
            Paragraph('Width(X) = ' + '{:.1f}'.format(box.Width()) + 'mm',
                      styles['Normal']))
        elements.append(
            Paragraph('Height(Y) = ' + '{:.1f}'.format(box.Height()) + 'mm',
                      styles['Normal']))
        elements.append(
            Paragraph('Thickness(Z) = ' + '{:.1f}'.format(box.Depth()) + 'mm',
                      styles['Normal']))

        elements.append(Paragraph('Tools', styles['Heading2']))
        for tool in self.tools.GetChildren():
            elements.append(
                Paragraph('T' + str(tool.tool_number) + ' ' + tool.GetTitle(),
                          styles['Normal']))

        elements.append(Paragraph('Tool Changes', styles['Heading2']))
        elements.append(
            Paragraph('to do with program.nc_code', styles['Normal']))

        # write the document to disk
        doc.build(elements)
Beispiel #8
0
def createpdf(request):
    cm = 2.54
    buffer = BytesIO()

    start = request.session['start']
    end = request.session['end']
    employee = request.user.employee
    reports = WorkTime.objects.filter(employee=employee, date__date__range=[start, end])
    data = [["Employee", "Date", "Start work", "IP start", "End work", "IP end", "Total hours"]]
    for report in reports:
        data.append([str(report.employee), str(report.date), str(report.start_work), str(report.start_ip_address), str(report.end_work), str(report.end_ip_address), str(report.hours_in_day)])

    pdf = SimpleDocTemplate(buffer, pagesize=A4, leftMargin=2.2 * cm, rightMargin=2.2 * cm, topMargin=6 * cm, bottomMargin=2.5 * cm)
    pdf.title = f"Timesheet {start} - {end} "

    table = Table(data)
    style = TableStyle([
        ('BACKGROUND', (0, 0), (-1, 0), colors.black),
        ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
        ('FONTSIZE', (0, 0), (-1, 0), 12),
        ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ('FONTSIZE', (0, 0), (-1, 0), 14),
        ('BACKGROUND', (0, 1), (-1, -1), colors.white),
        ('BOX', (0, 0), (-1, -1), 2, colors.black),
        ('GRID', (0, 1), (-1, -1), 1, colors.black)
    ])
    table.setStyle(style)

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Head1_center',
                              parent=styles['Heading1'],
                              alignment=TA_CENTER))

    styles.add(ParagraphStyle(name='Head2_center',
                              parent=styles['Heading2'],
                              alignment=TA_CENTER))

    elements = []

    elements.append(Paragraph(f'Timesheet: {employee}', styles['Head1_center']))
    elements.append(Paragraph(f'between {start} and {end}', styles['Head2_center']))
    elements.append(table)
    pdf.build(elements)

    buffer.seek(0)
    return FileResponse(buffer, as_attachment=False, filename='hello.pdf')
Beispiel #9
0
    def go_all(self):
        """Render the PDF for all items."""
        doc = SimpleDocTemplate(self.buf,
                                leftMargin=LEFTMARGIN,
                                rightMargin=RIGHTMARGIN)
        doc.title = self.filename
        doc.creator = "Romain Belia."
        doc.author = "Romain Belia."
        doc.subject = "Report created by Romain Belia."
        doc.keywords = ["report", "Romain Belia"]
        story = []
        # First Page

        story.append(self._build_title("Full Report"))
        story.append(Spacer(1, 1 * cm))
        for item in self.data:
            data = item['data']
            inventory = data['inventory'] if 'inventory' in data else []
            if 'id' in item:
                story.append(self._build_document_title("id", item['id']))
            if 'organization' in data:
                story.append(
                    self._build_document_title("organization",
                                               data['organization']))
            if 'reported_at' in data:
                story.append(
                    self._build_document_title("reported_at",
                                               data['reported_at']))
            if 'created_at' in data:
                story.append(
                    self._build_document_title("created_at",
                                               data['created_at']))
            story.append(Spacer(1, 1 * cm))
            story.append(Spacer(1, 1 * cm))
            if not inventory:
                story.append(self._build_no_content())
            for x in inventory:
                story.append(self._build_document_content(x))
                story.append(Spacer(1, 1 * cm))
            story.append(PageBreak())

        doc.build(story,
                  onFirstPage=self.firstpage,
                  onLaterPages=self.laterpages)
        return
Beispiel #10
0
    def build_doc(self, tables):
        """Build & return a simple PDF document from tables.

        tables: A list of DataTable instances. *

        * Required.
        """
        # Build a story out of the tables provided.
        common_style = [
            ('INNERGRID', (0, 0), (-1, -1), .25, colors.black),
            ('BOX', (0, 0), (-1, -1), .25, colors.black),
            ('FONT', (0, 0), (-1, -1), "Helvetica", 9),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ]
        story = []
        for table in tables:
            data_list = []
            for row in table.rows:
                data_list.append([cell.get_data() for cell in row])
            pdf_table = Table(data=data_list,
                              splitByRow=1,
                              repeatRows=1,
                              repeatCols=3,
                              colWidths=table.widths)
            pdf_table.setStyle(common_style + table.get_styles())
            story += [Spacer(1, 1 * inch), pdf_table]
            if table.page_break:
                story += [PageBreak()]
        if not story:
            story.append(Spacer(1, 1 * inch))
        # Generate & return a PDF from the story
        buff = BytesIO()
        doc = SimpleDocTemplate(buff, pagesize=pagesizes.A4)
        doc.title = self.title
        doc.author = "Report-maker"
        doc.subject = self.title
        doc.build(story,
                  onFirstPage=self.get_first_page(),
                  onLaterPages=self.get_later_pages())
        doc_pdf = buff.getvalue()
        buff.close()
        return doc_pdf
Beispiel #11
0
def create(nodenick):
    buffer = StringIO()
    doc = SimpleDocTemplate(buffer)
    doc.author = "dinemo"
    doc.subject = "Network monitoring report"
    doc.title = "Network monitoring report"
    Story = []
#   img = Image("dinemomaster/static/images/logo.jpg", 214, 50)
    img = Image("dinemomaster/static/images/logo.jpg", 107, 25)
    img.hAlign='RIGHT'
    Story.append(img)
    Story.append(Spacer(1,7 * cm))
    style = styles["title"]
    style.textColor = "darkblue"
    style.fontSize = 20
    Story.append(Paragraph("Network moritoring report", style))
    Story.append(Spacer(1,0.5 * cm))
    style.fontSize = 14
    Story.append(Paragraph("Generated on %s" % strftime("%d %h %Y"), style))
    if nodenick:
        style.fontSize = 16
        Story.append(Spacer(1,1 * cm))
        Story.append(Paragraph("            \"%s\" node network metrics""" % nodenick, style))
    style = styles["Normal"]
    style.textColor = "black"
    Story.append(PageBreak())




    for i in range(100):
        bogustext = ("Paragraph number %s. " % i) *20
        p = Paragraph(bogustext, style)
        Story.append(p)
        Story.append(Spacer(1,0.2*cm))

    doc.build(Story, onLaterPages= _later_page)
    pdf = buffer.getvalue()
    buffer.close()
    return pdf
Beispiel #12
0
def make_test(exam):

    # Set up custom fonts
    register_true_type_font()

    answers = False


    # Set up Doc properties
    styles = getSampleStyleSheet()
    
    if answers == True:
        doc = SimpleDocTemplate(f"exams/export/2021 {exam.name} ANSWERS.pdf",pagesize=letter)  
    else:
        doc = SimpleDocTemplate(f"exams/export/2021 {exam.name} Test.pdf",pagesize=letter)   

    doc_properties.Title = f"2021 {exam.name} Written Test"
    doc_properties.pageinfo = f"2021 {exam.name} Written Test"

    Story = [Spacer(1,.5*inch)]    
    style = styles["Normal"]   

    doc.leftMargin = 0.75 * inch
    doc.rightMargin = 0.75 * inch
    doc.title = '2021 State Conference Test'
    doc.auther = 'Pennsylvania TSA'

    for num, question, a, b, c, d, correct in zip(exam.numbers, exam.question, exam.choice_a, exam.choice_b, exam.choice_c, exam.choice_d, exam.correct):
        Story.append(IntegrateQuestions(num, question, a, b, c, d, correct, answers))
        Story.append(Spacer(0, 0.25*inch))

    # Append post-table text, if any
    Story.append(Spacer(0, 0.2*inch))  
    post_text = "This is the end of the test. Please submit your answer sheet."        
    p = Paragraph(post_text, style)
    Story.append(p)        

    # Finally, generate and save the PDF
    doc.build(Story, onFirstPage=FirstPage, onLaterPages=LaterPages)
Beispiel #13
0
def print_userlist(request):
    response = HttpResponse(mimetype='application/pdf')
    filename = u'filename=%s.pdf;' % _("Participant-list")
    response['Content-Disposition'] = filename.encode('utf-8')
    doc = SimpleDocTemplate(response)
    story = [Spacer(1,2*cm)]

    doc.title = _("List of Participants")
    # Table
    data= [['#', _('Last Name'), _('First Name'), _('Group'), _('Type'), _('Committee')]]
    sort = 'last_name'
    counter = 0
    for user in User.objects.all().order_by(sort):
        try:
            counter += 1
            user.get_profile()
            data.append([counter,
                    Paragraph(user.last_name, stylesheet['Tablecell']),
                    Paragraph(user.first_name, stylesheet['Tablecell']),
                    Paragraph(user.profile.group, stylesheet['Tablecell']),
                    Paragraph(user.profile.get_type_display(), stylesheet['Tablecell']),
                    Paragraph(user.profile.committee, stylesheet['Tablecell']),
                    ])
        except Profile.DoesNotExist:
            counter -= 1
            pass

    t=LongTable(data,
                    style=[
                        ('VALIGN',(0,0),(-1,-1), 'TOP'),
                        ('LINEABOVE',(0,0),(-1,0),2,colors.black),
                        ('LINEABOVE',(0,1),(-1,1),1,colors.black),
                        ('LINEBELOW',(0,-1),(-1,-1),2,colors.black),
                        ('ROWBACKGROUNDS', (0, 1), (-1, -1), (colors.white, (.9, .9, .9))),
                        ])
    t._argW[0]=0.75*cm
    story.append(t)
    doc.build(story, onFirstPage=firstPage, onLaterPages=laterPages)
    return response
Beispiel #14
0
def print_application(request, application_id=None):
    response = HttpResponse(mimetype='application/pdf')
    filename = u'filename=%s.pdf;' % _("Applications")
    response['Content-Disposition'] = filename.encode('utf-8')
    doc = SimpleDocTemplate(response)
    doc.title = None
    story = []
    
    if application_id is None:  #print all applications
        title = config_get("application_pdf_title")
        story.append(Paragraph(title, stylesheet['Heading1']))
        preamble = config_get("application_pdf_preamble")
        if preamble:
            story.append(Paragraph("%s" % preamble.replace('\r\n','<br/>'), stylesheet['Paragraph']))
        story.append(Spacer(0,0.75*cm))
        # List of applications
        for application in Application.objects.order_by('number'):
            if application.number:
                story.append(Paragraph(_("Application No.")+" %s: %s" % (application.number, application.title), stylesheet['Heading3']))
            else:
                story.append(Paragraph(_("Application No.")+"&nbsp;&nbsp;&nbsp;: %s" % (application.title), stylesheet['Heading3']))
        # Applications details (each application on single page)
        for application in Application.objects.order_by('number'):
            story.append(PageBreak())
            story = get_application(application, story)
    else:  # print selected application
        application = Application.objects.get(id=application_id)
        if application.number:
            number = application.number
        else:
            number = ""
        filename = u'filename=%s%s.pdf;' % (_("Application"), str(number))
        response['Content-Disposition'] = filename.encode('utf-8')
        story = get_application(application, story)

    doc.build(story, onFirstPage=firstPage, onLaterPages=firstPage)
    return response
hrefList = buscarHref(url)
listOfContent = buscarTabla(url)
#Crear PDF
doc = SimpleDocTemplate(nombreHistoria + ".pdf",
                        pagesize=letter,
                        rightMargin=72,
                        leftMargin=72,
                        topMargin=72,
                        bottomMargin=18)
Story = []  #Texto Final

photo = "1.jpg"

title = nombreHistoria
doc.title = nombreHistoria

book = descargarTodasLasPaginasYCapturarInfo(hrefList)

#photo
im = Image(photo, width=456.0, height=690.0)
Story.append(im)

styles = getSampleStyleSheet()

styles.add(ParagraphStyle(name='Justify',
                          alignment=TA_JUSTIFY))  #Definir la orientacion

styles.add(ParagraphStyle(name='center',
                          alignment=TA_CENTER))  #Definir la orientacion
Beispiel #16
0
 def run(self):
     linkbundle = self.link.split('/')[-3:][:2]
     if linkbundle[0] == interface.series:
         linkbundle[0] = '/'
     else:
         linkbundle[0] = '/' + linkbundle[0] + '/'
     ##Check if not downloaded already.
     try:
         chapters = os.listdir(interface.series)
     except:
         chapters = []
     if linkbundle[1] + '.pdf' in chapters and not interface.force:
         interface.completed = interface.completed + 1.0 / interface.seriesLen
         idle_add(
             self.update_status, interface.completed, 'Chapter ' +
             linkbundle[1].strip('c') + ' was found downloaded.')
         return True
         ##Completed that chapter!
     idle_add(self.update_status, None,
              'Start reading chapter ' + linkbundle[1].strip('c'))
     for page in range(1, 1000):
         url = 'http://mangafox.me/manga/' + interface.series + linkbundle[
             0] + linkbundle[1] + '/' + str(page) + '.html'
         request = urllib2.Request(url, interface.urllib, interface.headers)
         try:
             response = urllib2.urlopen(request)
             content = response.read()
             if response.info().get('Content-Encoding') == 'gzip':
                 content = gzip.GzipFile(fileobj=StringIO(content)).read()
         except Exception as e:
             print 'Could not get html for chapter ' + linkbundle[
                 1] + ' page ' + str(page)
             print 'Exception: {0}'.format(e)
             continue
         try:
             image = interface.regex.search(content).group(0)
             if not image in self.images:
                 self.images.append(image)
             else:
                 break  ##Chapter END
         except:
             print 'Could not get image for chapter ' + linkbundle[
                 1] + ' page ' + str(page)
             break  ##Could not get image!
     interface.completed = interface.completed + (0.25 /
                                                  interface.seriesLen)
     idle_add(self.update_status, interface.completed,
              'Downloading chapter ' + linkbundle[1].strip('c'))
     ###
     ##Downloading images.
     ###
     chapterLen = len(self.images)
     if chapterLen < 2:
         interface.completed = interface.completed + (0.75 /
                                                      interface.seriesLen)
         idle_add(self.update_status, interface.completed,
                  'Done chapter ' + linkbundle[1].strip('c'))
         return True
     try:
         os.mkdir(interface.series)
     except:
         pass
     try:
         os.mkdir(os.path.join(interface.series, linkbundle[1]))
     except:
         pass
     for image in self.images:
         imagename = image.split('/')[-1]
         img = open(
             os.path.join(interface.series, linkbundle[1], imagename), 'w')
         img.write(urllib2.urlopen(image).read())
         img.close()
         interface.completed = interface.completed + (
             0.5 / interface.seriesLen / chapterLen)
         idle_add(self.update_status, interface.completed, None)
     ###
     ##Making PDF
     ###
     c = SimpleDocTemplate(os.path.join(interface.series,
                                        linkbundle[1] + '.pdf'),
                           pagesize=interface.psize,
                           rightMargin=0,
                           leftMargin=0,
                           topMargin=0,
                           bottomMargin=0)
     Story = []
     maxh = interface.psize[1] - 20
     maxw = interface.psize[0] - 30
     title = ' '.join(interface.series.split('_'))
     c.title = title + ' ' + linkbundle[1]
     c.author = interface.author
     directory = os.path.join(interface.series, linkbundle[1])
     images = sorted(os.listdir(directory))
     for image in images:
         img = PImage.open(os.path.join(directory, image))
         width, height = img.size
         img = img.crop((0, 0, width, height - 40))
         img.save(os.path.join(directory, image))
         img = PImage.open(os.path.join(directory, image))
         width, height = img.size
         if width / maxw > height / maxh:
             height = height / (width / maxw)
             width = maxw
             if width > height:
                 img = img.rotate(90)
                 img.save(os.path.join(directory, image))
                 width, height = img.size
                 if width / maxw > height / maxh:
                     height = height / (width / maxw)
                     width = maxw
                 else:
                     width = width / (height / maxh)
                     height = maxh
         else:
             width = width / (height / maxh)
             height = maxh
         im = Image(os.path.join(directory, image), width, height)
         Story.append(im)
     c.build(Story)
     interface.completed = interface.completed + (0.2499 /
                                                  interface.seriesLen)
     idle_add(self.update_status, interface.completed,
              'Done chapter ' + linkbundle[1].strip('c'))
     interface.temps.append(os.path.join(interface.series, linkbundle[1]))
Beispiel #17
0
def generatepdf():
    '''This method generates summary pdf from the results of result processor.
    '''
    global result
    global exam

    doc = SimpleDocTemplate("report.pdf", pagesize=A4,
                            rightMargin=72, leftMargin=72,
                            topMargin=50, bottomMargin=30)
    Story = []
    doc.title = "Exam Result Summary"
    # Defining different text styles to be used in PDF
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Center1', alignment=1, fontSize=18))
    styles.add(ParagraphStyle(name='Center2', alignment=1, fontSize=13))
    styles.add(ParagraphStyle(name='Normal2', bulletIndent=20))
    styles.add(ParagraphStyle(name='Normal3', fontSize=12))
    for college in result:
        for branch in result[college]:
            # PDF Generation begins
            Story.append(Paragraph(college, styles["Center1"]))
            Story.append(Spacer(1, 0.25 * inch))
            Story.append(Paragraph(exam, styles["Center2"]))
            Story.append(Spacer(1, 12))
            numberofstudents = len(result[college][branch].itervalues().next())
            Story.append(Paragraph(branch, styles["Center2"]))
            Story.append(Spacer(1, 0.25 * inch))
            Story.append(Paragraph("Total Number of Students : %d" %
                         numberofstudents, styles["Normal2"]))
            Story.append(Spacer(1, 12))
            for subject in result[college][branch]:
                marklist = [int(result[college][branch][subject][x][0])
                            for x in result[college][branch][subject]]
                average = statistics.mean(marklist)  # Calculating mean
                stdev = statistics.pstdev(marklist)  # Calculating standard deviation
                passlist = {x for x in result[college][branch][
                    subject] if 'P' in result[college][branch][subject][x]}
                faillist = {x for x in result[college][branch][
                    subject] if 'F' in result[college][branch][subject][x]}
                absentlist = {x for x in result[college][branch][
                    subject] if 'AB' in result[college][branch][subject][x]}
                passcount = len(passlist)
                failcount = len(faillist)
                absentcount = len(absentlist)
                percentage = float(passcount) / numberofstudents
                subjectname = "<b>%s</b>" % subject
                passed = "<bullet>&bull;</bullet>Students Passed : %d" \
                    % passcount
                failed = " <bullet>&bull;</bullet>Students Failed : %d" \
                    % failcount
                absent = " <bullet>&bull;</bullet>Students Absent : %d" \
                    % absentcount
                percentage = " <bullet>&bull;</bullet>Pass Percentage : %.2f"\
                    % percentage
                average = " <bullet>&bull;</bullet>Average Marks : %.2f" \
                    % average
                stdev = "<bullet>&bull;</bullet>Standard Deviation : %.2f" \
                    % stdev
                Story.append(Paragraph(subjectname, styles["Normal"]))
                Story.append(Spacer(1, 12))
                Story.append(Paragraph(passed, styles["Normal2"]))
                Story.append(Spacer(1, 12))
                Story.append(Paragraph(failed, styles["Normal2"]))
                Story.append(Spacer(1, 12))
                Story.append(Paragraph(absent, styles["Normal2"]))
                Story.append(Spacer(1, 12))
                Story.append(Paragraph(percentage, styles["Normal2"]))
                Story.append(Spacer(1, 12))
                Story.append(Paragraph(average, styles["Normal2"]))
                Story.append(Spacer(1, 12))
                Story.append(Paragraph(stdev, styles["Normal2"]))
                Story.append(Spacer(1, 12))
            Story.append(PageBreak())  # Each department on new page
    doc.build(Story)
Beispiel #18
0
def generate_noise_report(files):
    sound_logs = []
    other_pdfs = []
    for uploaded_file in files:
        if uploaded_file.content_type == 'text/plain':
            sound_logs.append(uploaded_file.temporary_file_path())
        elif uploaded_file.content_type == 'application/pdf':
            other_pdfs.append(uploaded_file.temporary_file_path())
        else:
            raise Exception("File type {} is not text or PDF.".format(
                uploaded_file.content_type
            ))
    assert sound_logs, "No sound level data logs provided."
    (_fh1, report_filename) = tempfile.mkstemp(suffix='.pdf')
    (_fh2, assembled_filename) = tempfile.mkstemp(suffix='.pdf')
    try:
        doc = SimpleDocTemplate(report_filename, pagesize=letter)
        doc.title = title
        doc.author = author
        styles = getSampleStyleSheet()
        min_date = None
        story = []

        for filename in sound_logs:
            assert open(filename).readline().strip() == \
                'STANDARD HD600 DATA LOGGER SamplingRate:1.0;', \
                "Sound data logs must use HD600 format with 1-second samples."
            df = pd.read_csv(filename, sep=', ', header=None, skiprows=1,
                             names=['timestamp', 'level', 'unit'],
                             parse_dates=['timestamp'],
                             date_parser=parse_timestamp, engine='python')
            date = df['timestamp'].min().date()
            if not min_date or date < min_date:
                min_date = date
            unit = df['unit'].iloc[0]
            assert unit in ['dBA', 'dBC'], \
                "Sound must be measured in A/C-weighted decibels (dBA or dBC)."
            assert df['unit'].eq(unit).all(), \
                "Sound level units must be consistent."
            df['ratio'] = df['level'].apply(to_ratio)
            leq_fmt = "{overall:.1f} {dB} (over entire session)"
            if len(df) > 3600:
                leq_fmt += "\n{min:.1f} {dB} - {max:.1f} {dB} (rolling 1-hour)"
                df['leq'] = to_decibels(
                    df['ratio'].rolling(3600, center=True).mean()
                )
                df['leq'].fillna(method='bfill', inplace=True)
                df['leq'].fillna(method='ffill', inplace=True)
            else:
                df['leq'] = to_decibels(df['ratio'].mean())
            leq = leq_fmt.format(
                overall=to_decibels(df['ratio'].mean()),
                dB=unit,
                min=df['leq'].min(), max=df['leq'].max(),
            )
            story.append(Paragraph("Sound Level Monitoring Report",
                         styles["Title"]))
            story.append(Paragraph("Session Summary", styles["Heading2"]))
            story.append(Table([
                ['Start Time', df['timestamp'].iloc[0]],
                ['Stop Time', df['timestamp'].iloc[-1]],
                ['Duration', str(
                    df['timestamp'].iloc[-1] - df['timestamp'].iloc[0]
                ).replace('0 days ', '')],
                ['Device', 'HD600'],
                ['Lmin', '{} {}'.format(df['level'].min(), unit)],
                ['Lmax', '{} {}'.format(df['level'].max(), unit)],
                ['Leq', leq],
            ]))

            fig = Figure(figsize=(6, 4))
            ax = fig.add_subplot(1, 1, 1)
            ax.set_title("Logged Data")
            ax.set_xlabel("Time")
            ax.set_ylabel(unit)
            ax.grid(True)
            (line,) = ax.plot_date(df['timestamp'], df['level'], fmt='b-',
                                   linewidth=0.5)
            line.set_label("L")
            (line2,) = ax.plot_date(df['timestamp'], df['leq'], fmt='g-',
                                    linewidth=5, alpha=0.7)
            line2.set_label("Leq")
            for threshold in thresholds:
                ax.axhline(threshold, color='r', linestyle='--', alpha=0)
            ax.xaxis.set_major_formatter(DateFormatter('%H:%M'))
            ax.legend(loc='upper right', framealpha=0)

            fig.autofmt_xdate()
            buf = io.BytesIO()
            FigureCanvasAgg(fig).print_figure(buf, format='png')
            story.append(Image(buf))

            story.append(PageBreak())

        doc.build(story)
        subprocess.check_call([
            'gs', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-dQUIET',
            '-sDEVICE=pdfwrite', '-dPDFSETTINGS=/ebook',
            '-sPAPERSIZE=letter', '-dFIXEDMEDIA', '-dPDFFitPage',
            '-sOutputFile={}'.format(assembled_filename)
        ] + other_pdfs + [report_filename])
        with open(assembled_filename, 'rb') as f:
            pdf = f.read()
    finally:
        os.remove(report_filename)
        os.remove(assembled_filename)
    if min_date:
        filename = 'noise_{}.pdf'.format(min_date)
    else:
        filename = 'noise.pdf'
    return (pdf, filename)
Beispiel #19
0
        row = [name_p, 
               desc_col, 
               units_p, 
               dims_p]
        tab_data.append(row)           

    tab = Table(tab_data, colWidths=[1.8*inch,3.1*inch,0.6*inch,1.3*inch],
                repeatRows=1)
    tab.setStyle(TableStyle([('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), # Grid
                             ('BOX', (0,0), (-1,-1), 0.25, colors.black), # Grid
                             ('VALIGN', (0,0), (-1,-1), "TOP"), # Grid
                            ]))
    Story.append(tab)
    Story.append(Spacer(1, 20))
    

                     
###################### Final Stuff #####################
# Generation notes
text1 = 'This document was automatically generated on <font face="Courier">%s</font> using the file:'%t
text2 = '<font face="Courier">%s</font>' % (fn_in.split('/')[-1])
text3 = 'Software version: <font face="Courier">%s</font>' % (a['software_version'])
Story.append(Paragraph(text1, styles["Small"]))
Story.append(Paragraph(text2, styles["Small"]))
Story.append(Paragraph(text3, styles["Small"]))
Story.append(Spacer(1, 12))

doc.title = a['description']
doc.build(Story)

print 'Created %s' % fn_out
Beispiel #20
0
def make_trend_report(states, fname ):

	sorted = list()  # used to sort on different criteria
	for state in states:
		sorted.append(state)

	mysize = (700,1250)

	datestr = str(datetime.date.today()-datetime.timedelta(days=1))

	doc = SimpleDocTemplate(fname, pagesize=mysize)
	doc.title = 'State trends report ' + datestr
	doc.topMargin = 36

	elements = []

	styles=getSampleStyleSheet()
	NAnote = 'N/A - will never double under current trends'

	sorted.sort(key=sort_pos,reverse=True)
	single_trend_table( sorted, styles, elements, \
		'State trends by total positives', NAnote)

	sorted.sort(key=sort_active,reverse=True)
	single_trend_table( sorted, styles, elements, \
		'State trends by estimated active cases', NAnote)

	sorted.sort(key=sort_d1,reverse=True)
	single_trend_table( sorted, styles, elements, \
		'State trends by new cases', NAnote)

	sorted.sort(key=sort_d2,reverse=True)
	single_trend_table( sorted, styles, elements, \
		'State trends by by new case growth', NAnote)

	sorted.sort(key=sort_d3,reverse=True)
	single_trend_table( sorted, styles, elements, \
		'State trends by by new case growth acceleration', NAnote)

	sorted.sort(key=sort_dd1)
	single_trend_table( sorted, styles, elements, \
		'State trends by days to double new cases', NAnote)

	sorted.sort(key=sort_dmodel)
	single_trend_table( sorted, styles, elements, \
		'State trends by days to double total positives', \
		NAnote)

	sorted.sort(key=sort_amodel)
	single_trend_table( sorted, styles, elements, \
		'State trends by days to double active cases', \
		NAnote)

	sorted.sort(key=sort_ddpos)
	single_trend_table( sorted, styles, elements, \
		'State trends by days last doubling of total positives',\
			NAnote)

	sorted.sort(key=sort_ddact)
	single_trend_table( sorted, styles, elements, \
		'State trends by days for last doubling of active cases',\
			NAnote)

	# write the document to disk
	doc.build(elements)
Beispiel #21
0
def building(request, xy):
    global tutor, Class, sheet
    data = xy  #broadsheet_data(request)
    elements = []
    styles = getSampleStyleSheet()
    #styleNormal = styles['Normal']
    title_style = styles['Heading1']
    title_style.alignment = 1  #centered right 2 left 0
    title_style3 = styles['Heading3']
    title_style3.alignment = 1
    title_style4 = styles['Heading4']
    title_style4.alignment = 1
    title_style2 = styles['Heading5']
    title_style2.alignment = 1
    # PDF Text - Content
    Sum, mean, counts, Class, term, headers, sheet, tutor = data[1]
    elements.append(Paragraph('UMMUL-QURQH HIGH SCHOOL', title_style))
    elements.append(
        Paragraph('Arowona Bus-Stop, Akanran Road, Ibadan-Oyo state.',
                  title_style3))
    elements.append(
        Paragraph('[email protected], [email protected]', title_style4))
    elements.append(Paragraph('08053776177, 07042412052', title_style4))
    elements.append(Paragraph(sheet, title_style))

    #]# [(start_column, start_row), (end_column, end_row)]
    pdf_buffer = io.BytesIO()
    if sheet == 'BROADSHEET':
        x = [x * counts + x for x in range(4) if x != 0]
        t = Table(
            data[0],
            style=[
                ('BOX', (0, 0), (1, -1), 2, colors.red),
                ('LINEABOVE', (1, 2), (-2, 2), 1, colors.blue),
                ('LINEBEFORE', (2, 1), (2, -2), 1, colors.pink),
                ('FONTSIZE', (0, 0), (0, 2), 8),
                ('GRID', (0, 1), (17, counts), 2, colors.green),  #1st
                ('GRID', (0, counts + 2), (17, counts * 2), 2,
                 colors.blue),  #2nd
                ('GRID', (0, counts * 2 + 3), (17, counts * 3 + 2), 2,
                 colors.red),  #3rd
                ('GRID', (0, counts * 3 + 5), (17, -1), 2, colors.khaki),  #4th
                ('BACKGROUND', (0, 0), (17, 0), colors.limegreen),  #1st
                ('BACKGROUND', (0, x[0]), (17, x[0]), colors.orange),  #2nd
                ('BACKGROUND', (0, x[1]), (17, x[1]), colors.lavender),  #3rd
                ('BACKGROUND', (0, x[2]), (17, x[2]), colors.pink),  #4th
                ('BACKGROUND', (1, 1), (1, -1),
                 colors.lavender),  #student_name
                ('BACKGROUND', (14, 1), (17, -1), colors.orange),  #Annual
                ('BOX', (0, 0), (-1, -1), 2, colors.black),
                ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
                ('VALIGN', (3, 0), (3, 0), 'BOTTOM'),
                ('BACKGROUND', (5, 0), (5, -1), colors.khaki),  #Arb
                ('BACKGROUND', (9, 0), (9, -1), colors.khaki),  #Arb
                ('BACKGROUND', (13, 0), (13, -1), colors.khaki),  #Arb
                ('ALIGN', (3, 1), (3, 1), 'CENTER'),
                ('BACKGROUND', (14, 1), (17, 3), colors.beige),  #1st 3
                ('ALIGN', (3, 2), (3, 2), 'LEFT'),
            ])
        elements.append(t)
        elements.append(Spacer(inch, .25 * inch))
        elements.append(
            Paragraph(
                'Teacher-in-charge:- {}'.format(
                    tutor + ' ' + '---' + ' ' +
                    'Sign: {}'.format('_____________') +
                    'Date: {}'.format('________________')), title_style4))
        elements.append(
            Paragraph(
                'No of students Examined: {}'.format(counts) + ' ' + '---' +
                ' ' + str('Total Scores: {}'.format(Sum) + ' ' + '---' + ' ' +
                          'Average: {}'.format(mean) + '%'), title_style4))
        elements.append(
            Paragraph(
                'Approved by: {}'.format('_________________________________') +
                '  ' + 'Sign: {}'.format('__________' +
                                         'Date: {}'.format('_________')),
                title_style4))

        archivo_pdf = SimpleDocTemplate(pdf_buffer,
                                        pagesize=(landscape(letter)),
                                        rightMargin=40,
                                        leftMargin=40,
                                        topMargin=40,
                                        bottomMargin=40)
        archivo_pdf.watermark = os.path.join(settings.MEDIA_ROOT,
                                             'static/result/iiro.jpg')
        archivo_pdf.title = "{Class}.pdf".format(Class=str(Class))
        archivo_pdf.build(elements, onFirstPage=logo2, onLaterPages=broadsheet)
    else:  #]# [(start_column, start_row), (end_column, end_row)]
        if term == '3rd Term' + ' MarkSheet' and len(headers) != 9:
            t = Table(
                data[0],
                style=[
                    ('BOX', (0, 0), (-1, -1), 2, colors.black),
                    ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
                    ('BACKGROUND', (1, 1), (1, -1), colors.lavender),
                    ('BACKGROUND', (0, 0), (13, 0), colors.limegreen),  #1st
                    ('BACKGROUND', (12, 1), (-1, -1), colors.orange),  #1st
                    ('BACKGROUND', (5, 1), (11, -1), colors.grey),  #1st
                    ('BACKGROUND', (2, 1), (4, -1), colors.khaki),  #1st
                    ('BACKGROUND', (0, 1), (0, -1), colors.limegreen),  #1st
                ])
        else:
            t = Table(
                data[0],
                style=[
                    ('BOX', (0, 0), (-1, -1), 2, colors.black),
                    ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
                    ('BACKGROUND', (1, 1), (1, -1), colors.lavender),
                    ('BACKGROUND', (0, 0), (9, 0), colors.limegreen),  #1st
                    ('BACKGROUND', (8, 1), (-1, -1), colors.orange),  #1st
                    ('BACKGROUND', (5, 1), (7, -1), colors.grey),  #1st
                    ('BACKGROUND', (2, 1), (4, -1), colors.khaki),  #1st
                    ('BACKGROUND', (0, 1), (0, -1), colors.limegreen),  #1st
                ])
        elements.append(t)
        elements.append(Spacer(inch, .25 * inch))
        elements.append(
            Paragraph(
                'Teacher-in-charge:- {}'.format(
                    tutor + ' ' + '---' + ' ' +
                    'Sign: {}'.format('_____________') +
                    'Date: {}'.format('________________')), title_style4))
        elements.append(
            Paragraph(
                'No of students Examined: {}'.format(counts) + ' ' + '---' +
                ' ' + str('Total Scores: {}'.format(Sum) + ' ' + '---' + ' ' +
                          'Average: {}'.format(mean) + '%'), title_style4))
        elements.append(
            Paragraph(
                'Approved by: {}'.format('_________________________________') +
                '  ' + 'Sign: {}'.format('__________' +
                                         'Date: {}'.format('_________')),
                title_style4))
        archivo_pdf = SimpleDocTemplate(pdf_buffer,
                                        pagesize=(A4),
                                        rightMargin=40,
                                        leftMargin=40,
                                        topMargin=40,
                                        bottomMargin=40)
        archivo_pdf.watermark = os.path.join(settings.MEDIA_ROOT,
                                             'static/result/iiro.jpg')
        archivo_pdf.title = "{Class}.pdf".format(Class=str(Class))
        archivo_pdf.build(elements,
                          onFirstPage=logo,
                          onLaterPages=add_page_number)
        #archivo_pdf.showPage()

    pdf_buffer.seek(0)
    return FileResponse(pdf_buffer,
                        as_attachment=True,
                        filename=str(Class) + '.pdf')
Beispiel #22
0
        canvas.rotate(90)
        fs = canvas._fontsize
        canvas.translate(1, -fs/1.2)  # canvas._leading?
        canvas.setFont('Helvetica-Bold', 8)
        canvas.drawString(0, 0, self.text)

    def wrap(self, aW, aH):
        canv = self.canv
        fn, fs = canv._fontname, canv._fontsize
        return canv._leading, 1 + canv.stringWidth(self.text, fn, fs)


outpdfpath = 'output/05.pdf'
pdf = SimpleDocTemplate(outpdfpath, pagesize=landscape(A4), rightMargin=15,leftMargin=15,
                        topMargin=72,bottomMargin=18)
pdf.title = 'Class Report'

cols = ['Name', 'Age', 'Address']
cols = [verticalText(t) for t in cols]

data= [
    ['', '', ''],
    ['', '', ''],
    ['', '', ''],
    ['', '', ''],
    ['', '', ''],
    ['', '', ''],
    ['', '', ''],
    ['', '', ''],
    ['', '', ''],
]
Beispiel #23
0
    def create_pdf(
            self,
            title,
            df_films,
            top_10_films,
            worst_10_films,
            film_review_distro_path,
            top_10_cast,
            year_review_distro_path):
        """
        Creates the PDF from the information provided.

        Parameters
        ----------
        title                   {str}    the title of the document
        df_films                {object} the data frame of filmes, containing 'title', sum('sentiment_class')
        top_10_films            {object} the top 10 filmes, ordered by 'normalized_sentiment' desc
        worst_10_films          {object} the top 10 filmes, ordered by 'normalized_sentiment' asc
        film_review_distro_path {str}    path to the film review distibution image
        top_10_cast             {object} the top 10 artists, ordered by 'normalized_sentiment' desc
        year_review_distro_path {str}    path to the year bar chart image
        """
        output_path = f'{self.path_working_dir}/sentiment-{int(time.time())}.pdf'
        doc = SimpleDocTemplate(output_path, pagesize=A4, rightMargin=cm,
                                leftMargin=cm, topMargin=cm, bottomMargin=cm)
        doc.title = title
        width, _ = A4

        style_title = getSampleStyleSheet()["title"]
        style_h1 = getSampleStyleSheet()["h1"]
        style_normal = getSampleStyleSheet()["bu"]
        style_grid = TableStyle([
            ('GRID', (0, 0), (-1, -1), 1, black),
            ('ALIGN', (1, 0), (-1, -1), 'RIGHT')])

        br = Spacer(width, 20)

        elements = []
        elements.append(Paragraph(title, style=style_title))
        elements.append(Image(f'{self.path_images_dir}/header.png', width-(2*cm), 220))
        elements.append(br)

        elements.append(Paragraph('Executive Summary', style=style_h1))
        elements.append(Paragraph(f'The top film in our database, accorindg to TMDB reviews is <strong>{df_films.head(1).index[0]}</strong>', style=style_normal))
        elements.append(br)

        elements.append(Paragraph('Top 10 Films', style=style_h1))
        elements.append(Paragraph('Here are the top 10 films in our database, according to the sentiment found in the TMDb reviews, ranging from 0 (negative) to 5 (positive).', style=style_normal))
        elements.append(Table(top_10_films.copy().reset_index().to_numpy().tolist(), style=style_grid))
        elements.append(br)

        elements.append(Paragraph('Worst 10 Films', style=style_h1))
        elements.append(Paragraph('Here are the worst 10 films in our database, according to the sentiment found in the TMDb reviews, ranging from 0 (negative) to 5 (positive).', style=style_normal))
        elements.append(Table(worst_10_films.copy().reset_index().to_numpy().tolist(), style=style_grid))
        elements.append(br)

        elements.append(Paragraph('Review Sentiment Distibution', style=style_h1))
        elements.append(Image(film_review_distro_path))
        elements.append(br)

        elements.append(Paragraph('Top 10 Actors/Actresses in Best Reviewed Films', style=style_h1))
        elements.append(Paragraph('The ranking bellow is of actors that worked in films with positive reviews. Reviews are not made directly to actors, but to their films', style=style_normal))
        elements.append(Table(top_10_cast.copy().reset_index().to_numpy().tolist(), style=style_grid))
        elements.append(br)

        elements.append(Paragraph('IMDb Average Voting vs TMDb Sentiment Reviews', style=style_h1))
        elements.append(Image(year_review_distro_path))

        doc.build(elements)
        return output_path
Beispiel #24
0
def generateRecibido(request, idAgendaProc):
    
    recibidoFileName = "Documents/Reports/recibidoFile.pdf"
    
    docsAdjuntos = getListDocAdjunto(idAgendaProc)
    if(docsAdjuntos[0]):
        

        doc = SimpleDocTemplate(recibidoFileName, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18)
        
        Story = []
        logotipo = "Documents/Images/logo.png"

        formatoFecha = datetime.now()
        #fechaActual = formatoFecha.strftime("%A, %B %d de %Y")
        
        estilos = getSampleStyleSheet()
        estilos.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
        #texto = '%s' % fechaActual
        #Story.append(Paragraph(texto, estilos["Justify"]))
        Story.append(Spacer(1, 20))
        imagen = Image(logotipo, 1 * inch, 1 * inch)
        Story.append(imagen)
        Story.append(Spacer(1, 30))
        Story.append(Paragraph("ACUSE DE RECIBIDO", estilos["Title"]))
        Story.append(Spacer(1, 20))

        #Se obtienen las variables necesarias
        agenProc = AgendaProcedimiento.objects.get(pk=idAgendaProc)
        nombreAuxiliar=request.user.first_name + " " + request.user.last_name
        nombrePaciente = Persona.objects.get(pk=agenProc.idPaciente.idPersona).nombre
        fechaHoraProc = agenProc.fechaHora.strftime("%d/%m/%Y")

        #Consulta para el nombre del procedimiento
        idProcMod = agenProc.idProcedimientoModalidad.idProcedimientoModalidad
        codProc = ProcedimientoModalidad.objects.get(pk=idProcMod).codigoProcedimiento.codigoProcedimiento

        nombreProc = Procedimiento.objects.get(codigoProcedimiento=codProc).nombre

        Story.append(Spacer(1, 12))
        texto = 'Se confirma que el día %s el señor(a) %s a las %s, recibe la siguiente documentación:' % (formatoFecha.strftime("%d/%m/%Y"),
                                                                nombreAuxiliar,
                                                                formatoFecha.strftime("%I:%M %p")
                                                                )
        Story.append(Paragraph(texto, estilos["Normal"]))
        Story.append(Spacer(1, 25))

        algunDocumento = False
        iterator=1
        for docAdjunto in docsAdjuntos[1]:
            docAdjPath = docAdjunto.get('path')
            docAdjCodigo = docAdjunto.get('codigoDocumento')
            docAdjFechaRec = docAdjunto.get('fechaDocRecibido')
            docAdjNombre = Documento.objects.get(codigoDocumento=docAdjCodigo).nombre
            #Validar que tenga archivo adjunto
            if docAdjPath != "" and docAdjPath!=None:
                algunDocumento=True
                texto = ' %i.  %s con código %s recibido el %s' % (iterator,docAdjNombre, docAdjCodigo, docAdjFechaRec)
                Story.append(Paragraph(texto, estilos["Normal"]))
                iterator += 1
        if not algunDocumento:
            texto = '-NO se ha recibido ningún documento'
            Story.append(Paragraph(texto, estilos["Normal"]))    
        Story.append(Spacer(1, 25))
        texto = 'Del paciente %s, con fecha de programación tentativa de cirugía para el %s para realizar el procedimiento %s.' % (nombrePaciente,fechaHoraProc,nombreProc)
        Story.append(Paragraph(texto, estilos["Normal"]))
        Story.append(Spacer(1, 20))
        texto = 'Sinceramente,'
        Story.append(Paragraph(texto, estilos["Normal"]))
        Story.append(Spacer(1, 48))
        texto = '%s' % nombreAuxiliar
        Story.append(Paragraph(texto, estilos["Normal"]))
        Story.append(Spacer(1, 12))
        doc.title="Recibido para "+ nombrePaciente
        doc.build(Story)
        return FileResponse(open(recibidoFileName,'rb'))
    else:
        return JsonResponse({'error':'No existe agenda proc con id'},safe=False,status=status.HTTP_400_BAD_REQUEST)
Beispiel #25
0
    def pdf_Platypus(request, filtro):
        response = HttpResponse(content_type='application/pdf')  #tipo de rpta
        #pdf_name = "expedientes1.pdf"  # nombre para la descarga
        #response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name #descarga con el nombre indicado
        buff = BytesIO()  #almacena el doc
        #c = canvas.Canvas(buff)
        doc = SimpleDocTemplate(
            buff,
            pagesize=A4,
            rightMargin=50,  #miderecha
            leftMargin=50,  #mi izquierda
            topMargin=60,
            bottomMargin=70,  #inferior hoja                              
        )  #plantilla del doc enlazado al buffer
        expedientes = []  #lista para generar doc
        styles = getSampleStyleSheet()  #estilos
        style = styles['Title']
        style1 = styles['Normal']
        style.spaceAfter = 0.3 * inch
        style.fontSize = 21
        style.fontName = "Times-Roman"
        style.textColor = "Blue"

        #style.alignment=TA_JUSTIFY
        """p = ParagraphStyle('parrafos', 
						   
						   fontSize = 28,
						   fontName="Times-Roman")"""
        header = Paragraph("Listado de expedientes por " + filtro,
                           style)  #encabezado doc
        #header = Paragraph("Listado de expedientes", styles['Heading1'])#encabezado doc
        #header = Paragraph("Listado de expedientes", p)#encabezado doc
        """f=Image('static/img/admin.png', width=30, height=30)
		f.hAlign = 'LEFT'
		expedientes.append(f)
		expedientes.append(Spacer(1, 0.25*inch))"""
        expedientes.append(header)  #agrega encabezado del doc a lista
        headings = ('Nombre', 'Anio', 'descripcion', 'Procede'
                    )  #cabecera de tabla
        #filtro=request.GET['tipo']

        tipoexpediente = Tipoexpediente.objects.get(nombre=filtro)
        data = tipoexpediente.expediente_set.all()

        allclientes = [(Paragraph(p.nombre, style1), p.anio,
                        Paragraph(p.descripcion, style1),
                        Paragraph(str(p.serie), styles['Normal']))
                       for p in data]  #registros
        t = Table([headings] + allclientes,
                  colWidths=(50 * mm, 10 * mm, 70 * mm, 30 * mm),
                  repeatRows=1)  #crea tabla
        #t = Table([headings] + allclientes,repeatRows=1)#crea tabla
        t.setStyle(
            TableStyle([('GRID', (0, 0), (3, -1), 1, colors.dodgerblue),
                        ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue),
                        ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)
                        ]))  #estilos tabla
        expedientes.append(t)  #agrega tabla a lista

        #doc.build(expedientes) #genera doc en base a lista
        doc.title = "Listado de expedientes por " + filtro  # si no se coloca aparece anonymous
        doc.multiBuild(expedientes, canvasmaker=FooterCanvas)

        response.write(
            buff.getvalue())  #imprimimos el doc que sta en el buffer(pdf)
        buff.close()  #cerramos buffer
        return response  #retornamos pdf
Beispiel #26
0
def create_report():
    # получаем даты отчета
    r_from = report_from.get()
    r_by = report_by.get()
    # название pdf, показывается в шапке ридера
    title = f'Отчет по разрешенным съемных носителей информации ' \
            f'\nс {r_from} по {r_by}'
    # получаем данные между казанными датами
    select_query = '''SELECT * FROM journal_usb WHERE date_db BETWEEN (?) and (?) ORDER BY id_name;'''
    # полученные данные переводим в тип списка
    list_from_table = map(
        list, cursor.execute(select_query, (str(r_from), str(r_by))))
    # шапка в отчете
    headers = [
        'ID', 'ID СНИ', 'Фамилия', 'Имя', 'Отчество', 'Основание', 'Дата',
        'Примечание'
    ]
    temp_data = []
    for k in list_from_table:
        temp_data.append(k)
    # объединяем все полученные данные с шапкой
    temp_data.insert(0, headers)
    n = 0
    # тут запускаем ранее функцию для переноса не вмещяемых строк
    for k in temp_data:
        temp_data[n][7] = chop_line(k[7])
        n += 1
    # исползуем шрифт, т.к. reportlab не воспринимает кириллицу
    pdfmetrics.registerFont(TTFont('DejaVuSerif', 'DejaVuSerif.ttf', 'UTF-8'))
    # имя файла
    fileName = f'Отчет_СНИ_{r_from}_{r_by}.pdf'

    pdf = SimpleDocTemplate(fileName, pagesize=A4)
    pdf.title = title
    # указываем фиксированную ширину для "Комментарии"
    table = Table(temp_data,
                  colWidths=(None, None, None, None, None, None, None,
                             30 * mm))
    # указываем какой шрифт использовать для таблицы, т.к. если не указать, то кириллица не будет распознаваться
    style_sup_cyrillic = TableStyle([('FONTNAME', (0, 0), (-1, -1),
                                      'DejaVuSerif')])
    table.setStyle(style_sup_cyrillic)
    # дальше стилистика таблицы
    style_header = TableStyle([
        ('BACKGROUND', (0, 0), (8, 0), colors.fidblue),
        ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
        ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
    ])
    table.setStyle(style_header)

    rowNumb = len(temp_data)
    for i in range(1, rowNumb):
        if i % 2 == 0:
            bc = colors.burlywood
        else:
            bc = colors.beige
        ts = TableStyle([('BACKGROUND', (0, i), (-1, i), bc)])
        table.setStyle(ts)

    ts = TableStyle([('BOX', (0, 0), (-1, -1), 1, colors.black),
                     ('GRID', (0, 0), (-1, -1), 1, colors.black)])
    table.setStyle(ts)
    # создаем список значении
    elems = []
    elems.append(table)
    # создаем pdf, где добавляем таблицу и шапку для первой страницы и нумерацию для первой и последующие страницы
    pdf.build(elems,
              onFirstPage=report_first_page,
              onLaterPages=report_later_pages)
    msg_err('report_completed')
Beispiel #27
0
def make_mortality_report(states, fname ):

	sorted = list()  # used to sort on different criteria
	for state in states:
		sorted.append(state)
		state['eff_death'] = state['death'][state['n_samples']-1]
		state['eff_positives'] = \
			state['positives'][state['n_samples']-1]
		state['eff_positives14'] = \
			state['eff_positives'] - \
		(state['positives'][state['n_samples']-1] -\
			state['positives'][state['n_samples']-15])

	mysize = (700,1250)

	datestr = str(datetime.date.today()-datetime.timedelta(days=1))

	doc = SimpleDocTemplate(fname, pagesize=mysize)
	doc.title = 'State trends report ' + datestr
	doc.title = 'State mortality report ' + datestr
	doc.topMargin = 36

	elements = []

	styles=getSampleStyleSheet()
	NAnote = ''

	sorted.sort(key=sort_death,reverse=True)
	single_mortality_table( sorted, styles, elements, \
			'State mortality by total deaths', NAnote)

	sorted.sort(key=sort_death7,reverse=True)
	single_mortality_table( sorted, styles, elements, \
			'State daily mortality, by last 7 day average ', NAnote)

	sorted.sort(key=sort_mort_pos,reverse=True)
	single_mortality_table( sorted, styles, elements, \
			'State mortality by infected mortality rate', NAnote)

	sorted.sort(key=sort_mort_newpos,reverse=True)
	single_mortality_table( sorted, styles, elements, \
			'State mortality by newly infected mortality rate', NAnote)


	n_days=60
	for state in states:
		state['eff_death'] = state['death'][state['n_samples']-1] -\
			state['death'][state['n_samples']-(n_days+1)]
		state['eff_positives'] = \
		state['positives'][state['n_samples']-1] -\
			state['positives'][state['n_samples']-(n_days+1)]
		state['eff_positives14'] = \
			state['eff_positives'] - \
		(state['positives'][state['n_samples']-1] -\
			state['positives'][state['n_samples']-15])

	sorted.sort(key=sort_death,reverse=True)
	single_mortality_table(  sorted, styles, elements, \
			str(n_days) + ' day state mortality by deaths', NAnote)

	sorted.sort(key=sort_mort_pos,reverse=True)
	single_mortality_table( sorted, styles, elements, \
			str(n_days) + ' day state mortality by infected mortality rate', NAnote)

	sorted.sort(key=sort_mort_newpos,reverse=True)
	single_mortality_table( sorted, styles, elements, \
			str(n_days) + ' day state mortality by newly infected mortality rate', NAnote)


	# write the document to disk
	doc.build(elements)
Beispiel #28
0
def generate(doc_id):
    """given the document id generate a pdf string output
    """
    s = couchdb.Server(settings.COUCH_DSN)
    db = s['client_docs']
    doc = db.get(doc_id)

    if doc == None:
        raise Exception('Failed to generate pdf.',
                        'Document %s not found.' % doc_id)

    client_id = doc['client_id']

    engine = create_engine(settings.MYSQL_DSN)
    conn = engine.connect()

    output_stream = StringIO()
    doc_pdf = SimpleDocTemplate(output_stream)

    #get fname, lname
    sql = text("""SELECT fname, lname, company_name, company_address from leads
        WHERE id = :client_id
        """)
    client_details = conn.execute(sql, client_id=client_id).fetchone()

    doc_pdf.client_id = client_id
    doc_pdf.client_details = client_details
    doc_pdf.order_id = doc['order_id']

    #check clients running balance
    r = db.view('client/running_balance', key=client_id)

    if len(r.rows) == 0:
        doc_pdf.running_balance = Decimal(0)
    else:
        doc_pdf.running_balance = Decimal('%0.2f' % r.rows[0].value)

    sql = text("""SELECT sign from currency_lookup
        WHERE code = :currency
        """)
    doc_pdf.currency_sign = conn.execute(
        sql, currency=doc['currency']).fetchone()['sign']
    doc_pdf.currency = doc['currency']
    doc_pdf.total_amount = locale.format('%0.2f', Decimal(doc['total_amount']),
                                         True)

    if doc.has_key('invoice_date'):
        x = doc['invoice_date']
    else:
        x = doc['added_on']
    doc_pdf.invoice_date = date(x[0], x[1], x[2]).strftime('%B %d, %Y')

    if doc.has_key('pay_before_date'):
        x = doc['pay_before_date']
        doc_pdf.pay_before_date = date(x[0], x[1], x[2]).strftime('%B %d, %Y')

    #get client settings     for the removal of Available Balance
    now = get_ph_time(as_array=True)
    view = db.view('client/settings',
                   startkey=[client_id, now],
                   endkey=[client_id, [2011, 1, 1, 0, 0, 0, 0]],
                   descending=True,
                   limit=1,
                   include_docs=True)
    doc_client_settings = view.rows[0].doc
    show_available_balance = True
    if doc_client_settings.has_key('days_before_suspension'):
        if doc_client_settings['days_before_suspension'] == -30:
            show_available_balance = False

    doc_pdf.show_available_balance = show_available_balance

    #spacer
    Story = [Spacer(1, 3 * inch)]

    #collect items
    items = doc['items']
    items_has_date = False

    styles = getSampleStyleSheet()
    style_table = styles['Normal']
    style_table.fontSize = 8
    p_num_hours = Paragraph('<b>Number of Hours / Quantity</b>', style_table)
    p_hourly_rate = Paragraph(
        '<b>Hourly Rate / Unit Price %s</b>' % (doc_pdf.currency_sign),
        style_table)
    pdf_items = [
        [
            "Item", "Date", "Name and Designation of Staff", p_num_hours,
            p_hourly_rate,
            "Amount %s" % (doc_pdf.currency_sign)
        ],
    ]

    for item in items:
        item_date = ''
        if item.has_key('start_date'):
            items_has_date = True
            x = item['start_date']
            y = date(x[0], x[1], x[2])
            item_date += y.strftime('%b %d, %Y')

        if item.has_key('end_date'):
            items_has_date = True
            x = item['end_date']
            y = date(x[0], x[1], x[2])
            item_date += y.strftime(' - %b %d, %Y')

        description = Paragraph(item['description'], style_table)
        pdf_item = [
            item['item_id'],
            Paragraph(item_date, style_table), description,
            locale.format('%0.2f', Decimal(item['qty']), True),
            locale.format('%0.2f', Decimal(item['unit_price']), True),
            locale.format('%0.2f', Decimal(item['amount']), True)
        ]
        pdf_items.append(pdf_item)

    summary = []
    #append sub_total
    p_sub_total = Paragraph('<para alignment="right"><b>Sub Total</b></para>',
                            style_table)
    summary.append([
        p_sub_total, '', '', '', '',
        locale.format('%0.2f', Decimal(doc['sub_total']), True)
    ])

    #append gst
    p_gst = Paragraph('<para alignment="right"><b>GST</b></para>', style_table)
    summary.append([
        p_gst, '', '', '', '',
        locale.format('%0.2f', Decimal(doc['gst_amount']), True)
    ])

    #append total_amount
    p_total_amount = Paragraph(
        '<para alignment="right"><b>Total Amount</b></para>', style_table)
    summary.append([
        p_total_amount, '', '', '', '',
        '%s %s%s' %
        (doc_pdf.currency, doc_pdf.currency_sign,
         locale.format('%0.2f', Decimal(doc['total_amount']), True))
    ])

    grid_style = [
        ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),
        ('FONTSIZE', (0, 0), (-1, -1), 8),
        ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
        ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
        ('ALIGN', (0, 1), (0, -1), 'RIGHT'),
        ('ALIGN', (3, 1), (3, -1), 'RIGHT'),
        ('ALIGN', (4, 1), (4, -1), 'RIGHT'),
        ('ALIGN', (5, 1), (5, -1), 'RIGHT'),
    ]

    width_date = 1 * inch
    width_description = None
    if items_has_date == False:
        width_date = 0.4 * inch
        width_description = 3.5 * inch

    t = Table(pdf_items,
              colWidths=[
                  0.4 * inch, width_date, width_description, 0.6 * inch,
                  0.6 * inch, 1 * inch
              ],
              style=grid_style,
              repeatRows=1)
    Story.append(t)

    grid_style_summary = [
        ('FONTSIZE', (0, 0), (-1, -1), 8),
        ('ALIGN', (5, 0), (5, -1), 'RIGHT'),
        ('SPAN', (0, -1), (4, -1)),
        ('SPAN', (0, -2), (4, -2)),
        ('SPAN', (0, -3), (4, -3)),
        ('FONTNAME', (-1, -1), (-1, -1),
         'Helvetica-Bold'),  #bold total_amount figure
        ('BACKGROUND', (-1, -1), (-1, -1),
         colors.yellow),  #change background color or total_amount figure
        ('GRID', (-1, -3), (-1, -1), 0.5, colors.grey),
    ]
    t_summary = Table(summary,
                      colWidths=[
                          0.4 * inch, width_date, width_description,
                          0.6 * inch, 0.6 * inch, 1 * inch
                      ],
                      style=grid_style_summary)
    Story.append(t_summary)

    p = Paragraph("""HOW TO PAY:""", styleH2)
    Story.append(p)
    Story.append(Spacer(1, 0.1 * inch))

    styles = getSampleStyleSheet()
    style = styles["Normal"]
    style.borderWidth = 1
    style.borderRadius = 0.08 * inch
    style.borderPadding = 0.1 * inch
    style.fontName = 'Helvetica'
    style.borderColor = (0.22, 0.34, 0.53)
    style.backColor = (0.92, 0.96, 0.86)
    style.spaceAfter = 0.25 * inch

    #payment_link = 'https://remotestaff.com.au/portal/ClientTopUp/TopUp.html?order_id=%s' % doc['order_id']
    payment_link = 'https://remotestaff.com.au/portal/v2/payments/top-up/%s' % doc[
        'order_id']
    p = Paragraph(
        """
    <b>PAY ONLINE OR PHONE USING YOUR CREDIT CARD</b><br/>&nbsp<br/>
    We accept Visa, Master Card and AMEX. Follow this link <a color="blue" href="%s">%s</a>
    to pay for this invoice or call +61(02) 8014 9196 press 4 to pay over the phone.
    """ % (payment_link, payment_link), style)
    Story.append(p)

    debit_form_link = 'https://remotestaff.com.au/portal/pdf_report/credit_card_debit_form/THKGENDirectDebitForm.pdf'
    credit_card_form_link = 'https://remotestaff.com.au/portal/pdf_report/credit_card_debit_form/?id=%s' % client_id
    p = Paragraph(
        """
    <b>AUTO DEBIT</b><br/>&nbsp<br/>
    Have your account paid on the invoice due date automaticaly via direct debit or credit card to save time. Fill this form <a color="blue" href="%s">%s</a> (Australian Clients Only) or Credit Card form <a color="blue" href="%s">%s</a> and return to <a color="blue" href="mailto:[email protected]">[email protected]</a>
    """ % (debit_form_link, debit_form_link, credit_card_form_link,
           credit_card_form_link), style)
    Story.append(p)

    p = Paragraph(
        """
    <b>ELECTRONIC BANK TRANSFER TO</b><br/>&nbsp<br/>
    <b>Australia : </b><br/>
    Account Name: Think Innovations Pty. Ltd.<br/>
    BSB: 082 973<br/>
    Account Number: 49 058 9267<br/>
    Bank Branch: Darling Street, Balmain NSW 2041<br/>
    Swift Code: NATAAU3302S<br/>&nbsp<br/>
    <b>United Kingdom : </b><br/>
    Account Name: Think Innovations Pty. Ltd.<br/>
    UK Bank Address: HSBC. 25 Nothing Hill Gate. London. W11 3JJ<br/>
    Sort code: 40-05-09<br/>
    Acc: 61-50-63-23<br/>
    Swift Code: MIDLGB22<br/>
    IBAN Number: GB54MIDL40050961506323<br/>&nbsp;<br/>
    <b>United States : </b><br/>
    Account Name: Think Innovations Pty. Ltd.<br/>
    Bank Branch: HSBC Bank USA NA 452 Fifth Avenue, New York, NY 10018<br/>
    Account number: 048-984-515<br/>
    Routing Number: 021001088<br/>
    Swift code: MRMDUS33<br/>
    """, style)
    Story.append(p)

    p = Paragraph(
        """
    <b>Note:</b><br/>&nbsp;<br/>
    For Invoices in Australian Dollar a Merchant facility fees apply for the following credit card holders:
    <br/>
    """, styleN)
    Story.append(p)

    styleN.bulletIndent = 0.2 * inch
    p = Paragraph("""<br/><bullet>AMEX : 2%</bullet>""", styleN)
    Story.append(p)

    p = Paragraph("""<br/><bullet>Visa / MasterCard : 1%</bullet>""", styleN)
    Story.append(p)

    p = Paragraph(
        """<br/>For Invoices in Pounds and USD, 2% Merchant facility fees apply for all credit card payments.""",
        styleN)
    Story.append(p)

    p = Paragraph(
        """<br/>Paypal fees ranging from 1.1% - 2.4% of your invoice amount applies and will be reflected as a debit on your Available Balance Sheet.""",
        styleN)
    Story.append(p)

    p = Paragraph(
        """<br/>Note that we prefer payments made via bank transfer or direct debit.""",
        styleN)
    Story.append(p)

    Story.append(Spacer(1, 1 * inch))

    styles_ref_doc = getSampleStyleSheet()
    style_ref_doc = styles_ref_doc['Normal']
    style_ref_doc.fontName = 'Courier'
    style_ref_doc.fontSize = 9
    p = Paragraph(
        """
    -----------------------------------------<br/>
    Ref doc: %s
    -----------------------------------------<br/>
    """ % doc_id, style_ref_doc)
    Story.append(p)

    doc_pdf.title = 'INVOICE %s' % doc['order_id']
    doc_pdf.subject = 'doc_id %s' % doc['_id']
    doc_pdf.author = 'remotestaff'
    doc_pdf.creator = 'celery task generate_pdf_invoice.generate'
    doc_pdf.build(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)
    output_stream.seek(0)
    return output_stream.read()
Beispiel #29
0
	def get(self, request, *args, **kwargs):
		response = HttpResponse(content_type='application/pdf')#tipo de rpta
		#pdf_name = "fotos1.pdf"  # nombre para la descarga
		#response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name #descarga con el nombre indicado
		buff = BytesIO() #almacena el doc
		#c = canvas.Canvas(buff)
		doc = SimpleDocTemplate(buff,
								pagesize=A4,
								rightMargin=50,#miderecha
								leftMargin=50,#mi izquierda
								topMargin=60,
								bottomMargin=70,#inferior hoja                              
								)#plantilla del doc enlazado al buffer
		fotos = []#lista para generar doc
		styles = getSampleStyleSheet()#estilos
		style = styles['Title']
		style1= styles['Normal']
		style.spaceAfter = 0.3 * inch

		style.fontSize = 21
		style.fontName = "Times-Roman"
		style.textColor = "Blue"

		#style.alignment=TA_JUSTIFY
		"""p = ParagraphStyle('parrafos', 
						   
						   fontSize = 28,
						   fontName="Times-Roman")"""
		

		filtro = self.kwargs.get('filtro') # El mismo nombre que en tu URL<nombre>
		#pk = self.kwargs.get('pk') # El mismo nombre que en tu URL

		fotos.append(Spacer(1, 0.25*inch))#spacio antes del titulo
		header = Paragraph(self.titulo+filtro, style)#encabezado doc
		#header = Paragraph("Listado de Fotos", styles['Heading1'])#encabezado doc
		#header = Paragraph("Listado de Fotos", p)#encabezado doc
		
		"""f=Image('static/img/admin.png', width=30, height=30)
		f.hAlign = 'LEFT'
		fotos.append(f)
		fotos.append(Spacer(1, 0.25*inch))"""
		fotos.append(header)#agrega encabezado del doc a lista
		headings = self.lista_cabeceras#cabecera de tabla
		#headings = (self.campo1, self.campo2, self.campo3, self.campo4)#cabecera de tabla
		#filtro=request.GET['tipo']
		
		kwargs1 = {}
		kwargs1[self.maestrocampo] = filtro
	
		#eventos = Evento.objects.filter(**kargs) w
		objetofk = self.maestro.objects.get(**kwargs1)
		#tipofoto = self.maestro.objects.get(nombre=filtro)
		kwargs2 = {}
		kwargs2[self.modelcampo] = objetofk
		data=self.model.objects.filter(**kwargs2)
		#data=self.model.objects.filter(tipofoto=tipofoto)
		#data=tipofoto.foto_set.all()
		allclientes=[]
		
		for p in data:
			lista1=self.lista_datos
			
				#if f.name==self.lista_campos[0]:
			for campos in range(len(self.lista_campos)):

				#campo1=[Paragraph(str(p.campo(self.lista_campos[0])), style1)]
				lista1[campos]=[Paragraph(str(p.campo(self.lista_campos[campos])), style1)]
			
			registro=[lista1[0],lista1[1],lista1[2],lista1[3]]
			allclientes.append(registro)
			#allclientes.append([lista1[0],lista1[1],lista1[2],lista1[3]])#agrega cada registro en una lista extendiendola
			#allclientes.extend([lista])
			#allclientes.extend([(Paragraph(p.nombre, style1), p.anio, Paragraph(p.descripcion, style1), Paragraph(str(p.procedencia),styles['Normal']))])

		#allclientes = [(Paragraph(p.nombre, style1), p.anio, Paragraph(p.descripcion, style1), Paragraph(str(p.procedencia),styles['Normal'])) for p in data]#registros
		t = Table([headings] + allclientes,colWidths=self.anchocol,repeatRows=1)#crea tabla
		#t = Table([headings] + allclientes,repeatRows=1)#crea tabla
		t.setStyle(TableStyle(
			[
			('GRID', (0, 0), (3, -1), 1, colors.dodgerblue),
			('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue),
			('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)
			]
			))#estilos tabla
		fotos.append(t) #agrega tabla a lista

		#doc.build(fotos) #genera doc en base a lista
		doc.title = self.titulo+filtro # si no se coloca aparece anonymous
		doc.multiBuild(fotos, canvasmaker=FooterCanvas)

		response.write(buff.getvalue()) #imprimimos el doc que sta en el buffer(pdf)
		buff.close()#cerramos buffer
		return response #retornamos pdf
Beispiel #30
0
    def generatePDF(self, rollNum, log=False):
        """
        Generates the PDF based on the given data

        Parameters:

        rollNum: the roll number of the student whose PDF is to be made
        log=false: whether to log completion status or not
        """
        totalMarks = 0
        obtainedMarks = 0

        targetList = [
            key for key in self.__parsedCSV
            if key["Roll Number"] == str(rollNum)
        ]
        if len(targetList) == 0:
            raise Exception(
                "Specified Roll Number not found!! Please try again.")
        target = targetList[0]

        for key in target.keys():
            if key in self.__subjects and target[key]:
                totalMarks += self.__totalMarks[key]
                obtainedMarks += int(target[key])

        filename = (
            f"./pdfs/{target['Name'].replace(' ', '.')}-{target['Roll Number']}.pdf"
        )
        doc = SimpleDocTemplate(filename)
        doc.title = f"{target['Name']}'s Marksheet"
        doc.pagesize = portrait(LETTER)

        styles = getSampleStyleSheet()
        content = []
        styles["Normal"].fontName = fontName
        styles["Normal"].fontSize = 18
        styles["Normal"].spaceAfter = 10
        styles["Normal"].spaceBefore = 10

        styles["Heading1"].fontSize = 28
        styles["Heading1"].leading = 30

        styles["Heading2"].fontSize = 24
        styles["Heading2"].leading = 30

        content.append(
            Paragraph(
                f"<font name='Segoe UI'>{self.schoolname}</font>",
                styles["Heading1"],
            ), )
        content.append(
            Paragraph(
                f"<font name='Segoe UI'>{self.examname}</font>",
                styles["Heading2"],
            ))
        content.append(Spacer(1, 0.75 * inch))
        content.append(
            Paragraph(
                f"Name : {target['Name']}",
                styles["Normal"],
            ))
        content.append(
            Paragraph(f"Roll Number : {target['Roll Number']}",
                      styles["Normal"]))
        content.append(Spacer(1, 0.5 * inch))
        content.append(Paragraph("Marks :", styles["Normal"]))
        printMarksData = []
        for key, value in target.items():
            if key in self.__subjects and value:
                printMarksData.append([
                    key,
                    Paragraph(
                        f"<b>{value} / {self.__totalMarks[key]}</b>",
                        styles["Normal"],
                    ),
                ])

        marksTable = Table(printMarksData, colWidths="*")
        marksTable.setStyle(TABLESTYLE(len(printMarksData)))
        content.append(marksTable)

        content.append(Spacer(1, 0.5 * inch))

        overallData = []
        overallData.append([
            "Total Marks Obtained",
            Paragraph(
                f"<b>{obtainedMarks} / {totalMarks}</b>",
                styles["Normal"],
            ),
        ])
        overallData.append([
            "Percentage",
            Paragraph(
                f"<b>{(obtainedMarks / totalMarks) * 100:.2f}%</b>",
                styles["Normal"],
            ),
        ])
        overallTable = Table(overallData)
        overallTable.setStyle(TABLESTYLE(len(overallData)))
        content.append(overallTable)

        content.append(Spacer(1, 1 * inch))
        if self.signatureFile is not None:
            image = Image(
                self.signatureFile,
                width=3 * inch,
                height=1 * inch,
                kind="proportional",
            )
            image.hAlign = "LEFT"
            content.append(image)
        if self.authorityName is not None:
            styles["Normal"].fontSize = 16
            content.append(Paragraph(self.authorityName, styles["Normal"]))

        if log:
            print(f"Saved {target['Name']}'s Marksheet in {filename}")
        doc.build(content)
 def run(self):
     linkbundle = self.link.split('/')[-3:][:2]
     if linkbundle[0] == interface.series:
         linkbundle[0] = '/'
     else:
         linkbundle[0] = '/'+linkbundle[0]+'/'
     ##Check if not downloaded already.
     try:
         chapters = os.listdir(interface.series)
     except:
         chapters = []
     if linkbundle[1]+'.pdf' in chapters and not interface.force:
         interface.completed = interface.completed+1.0/interface.seriesLen
         idle_add(self.update_status, interface.completed, 'Chapter '+linkbundle[1].strip('c')+' was found downloaded.')
         return True
         ##Completed that chapter!
     idle_add(self.update_status, None, 'Start reading chapter '+linkbundle[1].strip('c'))
     for page in range(1, 1000):
         url = 'http://www.mangafox.com/manga/'+interface.series+linkbundle[0]+linkbundle[1]+'/'+str(page)+'.html'
         request = urllib2.Request(url, interface.urllib, interface.headers)
         try:
             content = urllib2.urlopen(request).read()
         except:
             continue
         try:
             image=interface.regex.search(content).group(0)
             if not image in self.images:
                 self.images.append(image)
             else:
                 break ##Chapter END
         except:
             print 'Could not get image for chapter '+linkbundle[1]+' page '+str(page)
             break ##Could not get image!
     interface.completed = interface.completed+(0.25/interface.seriesLen)
     idle_add(self.update_status, interface.completed, 'Downloading chapter '+linkbundle[1].strip('c'))
     ###
     ##Downloading images.
     ###
     chapterLen = len(self.images)
     if chapterLen < 2:
         interface.completed = interface.completed+(0.75/interface.seriesLen)
         idle_add(self.update_status, interface.completed, 'Done chapter '+linkbundle[1].strip('c'))
         return True
     try:
         os.mkdir(interface.series)
     except:
         pass
     try:
         os.mkdir(os.path.join(interface.series, linkbundle[1]))
     except:
         pass
     for image in self.images:
         imagename=image.split('/')[-1]
         img = open(os.path.join(interface.series, linkbundle[1], imagename), 'w')
         img.write(urllib2.urlopen(image).read())
         img.close()
         interface.completed = interface.completed+(0.5/interface.seriesLen/chapterLen)
         idle_add(self.update_status, interface.completed, None)
     ###
     ##Making PDF
     ###
     c=SimpleDocTemplate(os.path.join(interface.series, linkbundle[1]+'.pdf'),
                         pagesize=interface.psize,
                         rightMargin=0,
                         leftMargin=0,
                         topMargin=0,
                         bottomMargin=0)
     Story=[]
     maxh = interface.psize[1]-20
     maxw = interface.psize[0]-30
     title=' '.join(interface.series.split('_'))
     c.title=title+' '+linkbundle[1]
     c.author=interface.author
     directory=os.path.join(interface.series, linkbundle[1])
     images=sorted(os.listdir(directory))
     for image in images:
         img = PImage.open(os.path.join(directory, image))
         width, height = img.size
         img = img.crop(( 0, 0, width, height-40))
         img.save(os.path.join(directory, image))
         img = PImage.open(os.path.join(directory, image))
         width, height = img.size
         if width/maxw>height/maxh:
             height=height/(width/maxw)
             width=maxw
             if width>height:
                 img = img.rotate(90)
                 img.save(os.path.join(directory, image))
                 width, height = img.size
                 if width/maxw>height/maxh:
                     height=height/(width/maxw)
                     width=maxw
                 else:
                     width=width/(height/maxh)
                     height=maxh
         else:
             width=width/(height/maxh)
             height=maxh
         im = Image(os.path.join(directory, image), width, height)
         Story.append(im)
     c.build(Story)
     interface.completed = interface.completed+(0.2499/interface.seriesLen)
     idle_add(self.update_status, interface.completed, 'Done chapter '+linkbundle[1].strip('c'))
     interface.temps.append(os.path.join(interface.series, linkbundle[1]))