示例#1
0
    def pdf_body(self, data, number):
        stylesheet = Styles.getSampleStyleSheet()

        TitleStyle = stylesheet[self.styles['title']['name']]
        TitleStyle.alignment = self.styles['title']['align']

        SummaryStyle = stylesheet[self.styles['summary']['name']]
        SummaryStyle.alignment = self.styles['summary']['align']

        CVEStyle = stylesheet[self.styles['cve']['name']]
        CVEStyle.alignment = self.styles['cve']['align']

        CVEInfoStyle = stylesheet[self.styles['cve_info']['name']]
        CVEInfoStyle.alignment = self.styles['cve_info']['align']

        CVEDescStyle = stylesheet[self.styles['cve_description']['name']]
        CVEDescStyle.alignment = self.styles['cve_description']['align']

        CVELinksStyle = stylesheet[self.styles['cve_link']['name']]
        CVELinksStyle.alignment = self.styles['cve_link']['align']

        body = list()
        body.append(Paragraph(
            '{} #{}'.format(self.template['title'], number), TitleStyle))

        body.append(Spacer(Units.inch, Units.inch/4))

        body.append(Paragraph(self.template['description'], SummaryStyle))

        body.append(Spacer(Units.inch, Units.inch/4))

        cve_table, text = self.parse_json(data)

        table = Table(cve_table)
        table.setStyle(TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, Colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, Colors.black)
        ]))

        body.append(table)

        body.append(PageBreak())

        for i in text:
            body.append(Paragraph(i['label'], CVEStyle))
            body.append(Paragraph('Description:', CVEInfoStyle))
            body.append(Paragraph(i['description'], CVEDescStyle))
            body.append(Paragraph('External Links:', CVEInfoStyle))
            body.append(Paragraph(
                '* <font color="{}">NIST</font>: <font color="{}">{}</font>'
                    .format(self.styles['cve_label_color'],
                            self.styles['cve_link_color'],
                            self.template['nist_url'].format(i['name'])),
                CVELinksStyle))
            body.append(Paragraph(
                '* <font color="{}">MITRE</font>: <font color="{}">{}</font>'
                    .format(self.styles['cve_label_color'],
                            self.styles['cve_link_color'],
                            self.template['mitre_url'].format(i['name'])),
                CVELinksStyle))
            for link in i['reference']:
                body.append(Paragraph(
                    '* <font color="{}">{}</font>'
                        .format(self.styles['cve_link_color'], link),
                    CVELinksStyle))
            body.append(Spacer(Units.inch, Units.inch/4))

        return body
示例#2
0
文件: kassia.py 项目: ilizol/kassia
    def create_pdf(self):
        """Create a PDF output file."""
        for child_elem in self.bnml:
            if child_elem.tag in ['header-even', 'header']:
                default_header_style = self.styleSheet['Header']
                header_attrib_dict = self.fill_attribute_dict(
                    child_elem.attrib)
                if 'style' in header_attrib_dict:
                    default_header_style = getattr(self.styleSheet,
                                                   header_attrib_dict['style'],
                                                   'Header')
                header_style = self.merge_paragraph_styles(
                    default_header_style, header_attrib_dict)
                header_text = child_elem.text.strip()
                self.header_even_paragraph: Paragraph = Paragraph(
                    header_text, header_style)

                for embedded_attrib in child_elem:
                    if embedded_attrib.tag is not None and embedded_attrib.tag == 'page-number':
                        pagenum_attrib_dict = self.fill_attribute_dict(
                            embedded_attrib.attrib)
                        self.header_even_pagenum_style = self.merge_paragraph_styles(
                            default_header_style, pagenum_attrib_dict)

            if child_elem.tag == 'header-odd':
                default_header_style = self.styleSheet['Header']
                header_attrib_dict = self.fill_attribute_dict(
                    child_elem.attrib)
                if 'style' in header_attrib_dict:
                    default_header_style = getattr(self.styleSheet,
                                                   header_attrib_dict['style'],
                                                   'Header')
                header_style = self.merge_paragraph_styles(
                    default_header_style, header_attrib_dict)
                header_text = child_elem.text.strip()
                self.header_odd_paragraph: Paragraph = Paragraph(
                    header_text, header_style)

                for embedded_attrib in child_elem:
                    if embedded_attrib.tag is not None and embedded_attrib.tag == 'page-number':
                        pagenum_attrib_dict = self.fill_attribute_dict(
                            embedded_attrib.attrib)
                        self.header_odd_pagenum_style = self.merge_paragraph_styles(
                            default_header_style, pagenum_attrib_dict)

            if child_elem.tag == 'footer':
                default_footer_style = self.styleSheet['Footer']
                footer_attrib_dict = self.fill_attribute_dict(
                    child_elem.attrib)
                if 'style' in footer_attrib_dict:
                    default_footer_style = getattr(self.styleSheet,
                                                   footer_attrib_dict['style'],
                                                   'Footer')
                footer_style = self.merge_paragraph_styles(
                    default_footer_style, footer_attrib_dict)
                footer_text = child_elem.text.strip()
                self.footer_paragraph: Paragraph = Paragraph(
                    footer_text, footer_style)
                for embedded_attrib in child_elem:
                    if embedded_attrib.tag is not None and embedded_attrib.tag == 'page-number':
                        pagenum_attrib_dict = self.fill_attribute_dict(
                            embedded_attrib.attrib)
                        self.footer_pagenum_style = self.merge_paragraph_styles(
                            default_footer_style, pagenum_attrib_dict)

            if child_elem.tag == 'pagebreak':
                self.story.append(PageBreak())

            if child_elem.tag == 'linebreak':
                space = child_elem.attrib.get('space', '30')
                space_amt = int(space)
                self.story.append(Spacer(0, space_amt))

            if child_elem.tag == 'paragraph':
                paragraph_attrib_dict = self.fill_attribute_dict(
                    child_elem.attrib)
                self.draw_paragraph(child_elem, paragraph_attrib_dict)

            if child_elem.tag == 'troparion':
                neumes_list = []
                lyrics_list = []
                dropcap = None

                for troparion_child_elem in child_elem:
                    if troparion_child_elem.tag == 'pagebreak':
                        self.story.append((PageBreak()))

                    if troparion_child_elem.tag == 'neumes':
                        neumes_elem = troparion_child_elem
                        attribs_from_bnml = self.fill_attribute_dict(
                            neumes_elem.attrib)
                        neumes_style = self.merge_paragraph_styles(
                            self.styleSheet['Neumes'], attribs_from_bnml)
                        # Get font family name without 'Main', 'Martyria', etc.
                        font_family_name, _ = neumes_style.fontName.rsplit(
                            ' ', 1)
                        neume_config = self.neume_info_dict[font_family_name]

                        for neume_chunk in neumes_elem.text.strip().split():
                            # Check for ligatures and conditionals, if none, build from basic neume parts
                            neume_name_list = self.find_neume_names(
                                neume_chunk, neume_config)
                            for neume_name in neume_name_list:
                                try:
                                    neume = self.create_neume(
                                        neume_name, neume_config,
                                        neumes_style.fontName, neumes_style)
                                    if neume:  # neume will be None if neume not found
                                        neumes_list.append(neume)
                                except KeyError as ke:
                                    logging.error(
                                        "Couldn't add neume: {}. Check bnml for bad symbol and verify glyphnames.yaml is correct."
                                        .format(ke))

                    if troparion_child_elem.tag == 'lyrics':
                        lyrics_elem = troparion_child_elem
                        lyrics_style = self.styleSheet['Lyrics']
                        attribs_from_bnml = self.fill_attribute_dict(
                            lyrics_elem.attrib)
                        lyrics_style = self.merge_paragraph_styles(
                            lyrics_style, attribs_from_bnml)

                        for lyric_text in lyrics_elem.text.strip().split():
                            lyric = Lyric(text=lyric_text,
                                          font_family=lyrics_style.fontName,
                                          font_size=lyrics_style.fontSize,
                                          color=lyrics_style.textColor,
                                          top_margin=lyrics_style.spaceBefore)
                            lyrics_list.append(lyric)

                    if troparion_child_elem.tag == 'dropcap':
                        dropcap_elem = troparion_child_elem
                        dropcap_style = self.styleSheet['Dropcap']
                        if dropcap_elem.attrib:
                            attribs_from_bnml = self.fill_attribute_dict(
                                dropcap_elem.attrib)
                            dropcap_style = self.merge_paragraph_styles(
                                dropcap_style, attribs_from_bnml)
                        dropcap_text = dropcap_elem.text.strip()
                        dropcap = Dropcap(dropcap_text,
                                          dropcap_style.rightIndent,
                                          dropcap_style)

                if neumes_list:
                    self.draw_troparion(neumes_list, lyrics_list, dropcap)

        try:
            self.doc.build(self.story,
                           onFirstPage=self.draw_header_footer,
                           onEvenPages=self.draw_header_footer,
                           onOddPages=self.draw_header_footer)
        except IOError:
            logging.error("Could not save XML file.")
示例#3
0
    def new_club(self, club):
        """
        Add a club on a new page
        :param club: Club to print
        :type club: Club
        """
        logging.debug("New club: " + club.nom)
        if not self.story:
            # For the first page
            self.club = club
        else:
            self.story.append(NextPageTemplate(club))
            self.story.append(PageBreak())

        table_style = header_table_style["Club"]
        table = Table([[club.nom]], [self.page_width], 2 * cm, style=table_style)
        table.link_object = (club, club.nom)
        self.story.append(table)

        table_style = header_table_style["Content"]

        for departemental in (True, False):
            total = 0
            if departemental:
                competitions = [c for c in club.competitions if c.departemental() and c.competition_link is None]
                self.story.append(Paragraph("Compétitions départementales", sHeading2))
                bonus = self.bonus[club.departement_name()]
            else:
                competitions = [c for c in club.competitions if not c.departemental() and c.competition_link is None]
                self.story.append(Paragraph("Compétitions régionales et plus", sHeading2))
                bonus = self.bonus["Régional"]

            # TODO: Remove clubs with departement != 06
            if departemental and club.departement != "06":
                self.story.append(Paragraph("Pas d'information départementale", sNormal))
                continue

            table_data = [["Compétition", "Réunion", "Points"]]

            for competition in sorted(competitions, key=lambda c: c.startdate):
                description = [Paragraph("{} - {}".format(competition.date_str(), competition.titre()), sNormal)]
                for c in competition.linked:
                    description.append(Paragraph("{} - {}".format(c.date_str(), c.titre()), sNormal))

                row = [description, [], []]
                for reunion in competition.reunions:
                    pts = reunion.points(club)
                    total += pts
                    row[1].append(Paragraph("<a href='#{}'>{}</a>".format(reunion.link(), reunion.titre), sNormal))
                    row[2].append(Paragraph("{} points".format(pts), sNormal))
                table_data.append(row)

            table = Table(table_data, [self.page_width * x for x in (0.70, 0.15, 0.15)], style=table_style)
            self.story.append(table)
            self.story.append(Paragraph("<br/>Total des points: {}".format(total), sNormal))

            if total < 0:
                self.story.append(Paragraph("Valeur du malus: {:.2f} €".format(total * 10), sNormal))
            else:
                self.story.append(Paragraph("Valeur du bonus (Estimation): {:.2f} €"
                                            .format(total * bonus), sNormal))

        self.story.append(Paragraph("Liste des officiels", sHeading2))
        if len(club.officiels.keys()) == 0:
            self.story.append(Paragraph("Pas d'officiel pour le club", sNormal))
        else:
            self.story.append(Paragraph("Lorsqu'un officiel est inscrit pour plusieurs poste, un seul est retenu.",
                                        sNormal))

            officiels = sorted(club.officiels.keys(), key=lambda o: o.nom)
            for officiel in officiels:
                table_data = [["{} {} ({}) - {} participations".format(officiel.prenom, officiel.nom, officiel.niveau,
                                                                       len(club.officiels[officiel].values())),
                               "Réunion", "Rôle"]]

                competitions = dict()
                for reunion, poste in club.officiels[officiel].items():
                    if reunion.competition not in competitions:
                        competitions[reunion.competition] = []
                    competitions[reunion.competition].append((reunion, poste))

                for competition in sorted(competitions.keys(), key=lambda c: c.startdate):
                    description = [Paragraph("{} - {}".format(competition.date_str(), competition.titre()), sNormal)]
                    row = [description, [], []]
                    for c in competition.linked:
                        description.append(Paragraph("{} - {}".format(c.date_str(), c.titre()), sNormal))

                    for reunion, poste in competitions[competition]:
                        row[1].append(Paragraph("<a href='#{}'>{}</a>".format(reunion.link(), reunion.titre), sNormal))
                        row[2].append(Paragraph(poste, sNormal))
                    table_data.append(row)

                table_style = header_table_style["Content"]
                table = Table(table_data, [self.page_width * x for x in (0.65, 0.15, 0.20)], style=table_style)
                self.story.append(Paragraph("&nbsp;", sNormal))
                self.story.append(table)
示例#4
0
def build(posting_name, company, company_address, name, address, phone, email,
          github_account, keywords, education_list, number_educations,
          skill_section, number_skills, experience_list, number_exp,
          references, number_ref, award_section, number_award, volunteering,
          number_vol, hobbies, number_hobbies, cover):
    '''
    Function to build a resume and produce its pdf
    :param posting_name: string name of the posting
    :param company: string name of company or None
    :param company_address: string address of company or none
    :param name: string of persons full name
    :param address: string of persons address
    :param phone: string of persons phone
    :param email: string of persons email
    :param github_account: string of persons github
    :param keywords: string list of scraped keywords
    :param education_list: Education list of persons educational experience
    :param number_educations: number of Education experiences you want on the resume
    :param skill_section: SkillSection or Skill list object containing the a persons skills as Skill objects
    :param number_skills: number of skills you want on resume - is a list of size 4 if using SkillSection object
                            in skill_section or just an integer if using a list in skill_section
    :param experience_list: Experience list of persons non-educational experiences
    :param number_exp: number of non-educational experiences you want on the list
    :param references: References list of a persons references
    :param number_ref: number of references you want on your resume
    :param award_section: Award list of a persons awards
    :param number_award: number of awards you want on the resume
    :param volunteering: Volunteering list of a persons volunteering experience
    :param number_vol: number of volunteering experiences you want on the list
    :param hobbies: Other list of a persons hobbies
    :param number_hobbies: number of hobbies you want on the resume
    :param cover: boolean on whether you want a cover_letter or not
    :post-condition: produces a PDF of the tailored resume in the same folder is Main.py
    :return: N/A
    '''
    ###################################################################################################################
    # first organizing skills
    # organize skills
    all_skills = None
    if keywords != None:
        if isinstance(skill_section, SkillSection):
            assert isinstance(number_skills, list) and len(number_skills) == 4, \
                'number_skills needs to be a list for skill_section of type SkillSection!'

            all_skills = SkillSection()
            # language skills
            count = 0
            section = skill_section.get_language()
            section.sort(key=object_precedence, reverse=True)
            for skill in section:
                if count >= number_skills[0]:
                    break
                elif len([i
                          for i in skill.get_keywords() if i in keywords]) > 0:
                    all_skills.add_language(skill)
                    count += 1
            if count < number_skills[0]:
                for skill in section:
                    if count >= number_skills[0]:
                        break
                    elif skill not in all_skills.get_language():
                        all_skills.add_language(skill)
                        count += 1

            # technical skills
            count = 0
            section = skill_section.get_technical()
            section.sort(key=object_precedence, reverse=True)
            for skill in section:
                if count >= number_skills[1]:
                    break
                elif len([i
                          for i in skill.get_keywords() if i in keywords]) > 0:
                    all_skills.add_technical(skill)
                    count += 1
            if count < number_skills[1]:
                for skill in section:
                    if count >= number_skills[1]:
                        break
                    elif skill not in all_skills.get_technical():
                        all_skills.add_technical(skill)
                        count += 1

            # interpersonal skills
            count = 0
            section = skill_section.get_interpersonal()
            section.sort(key=object_precedence, reverse=True)
            for skill in section:
                if count >= number_skills[2]:
                    break
                elif len([i
                          for i in skill.get_keywords() if i in keywords]) > 0:
                    all_skills.add_interpersonal(skill)
                    count += 1
            if count < number_skills[2]:
                for skill in section:
                    if count >= number_skills[2]:
                        break
                    elif skill not in all_skills.get_interpersonal():
                        all_skills.add_interpersonal(skill)
                        count += 1

            # other skills
            count = 0
            section = skill_section.get_other()
            section.sort(key=object_precedence, reverse=True)
            for skill in section:
                if count >= number_skills[3]:
                    break
                elif len([i
                          for i in skill.get_keywords() if i in keywords]) > 0:
                    all_skills.add_other(skill)
                    count += 1
            if count < number_skills[3]:
                for skill in section:
                    if count >= number_skills[3]:
                        break
                    elif skill not in all_skills.get_other():
                        all_skills.add_other(skill)
                        count += 1

        elif isinstance(skill_section, list):
            assert isinstance(
                number_skills,
                int), 'number_skills must be int for skill_section type list'
            skill_section.sort(reverse=True, key=object_precedence())
            all_skills = []
            count = 0
            for skill in skill_section:
                if count >= number_skills:
                    break
                elif len([i
                          for i in skill.get_keywords() if i in keywords]) > 0:
                    all_skills.append(skill)
                    count += 1
            if count < number_skills:
                for skill in skill_section:
                    if count >= number_skills:
                        break
                    elif skill not in all_skills:
                        all_skills.append(skill)
                        count += 1

    # organize education
    all_education = None
    count = 0
    if isinstance(education_list, list):
        all_education = []
        education_list.sort(key=object_precedence, reverse=True)
        for educ in education_list:
            if count < number_educations:
                all_education.append(educ)
                count += 1
    elif isinstance(education_list, str):
        all_education = education_list

    # organize experiences
    all_experiences = None
    count = 0
    if isinstance(experience_list, list):
        all_experiences = []
        experience_list.sort(key=object_precedence, reverse=True)
        for exp in experience_list:
            if count < number_exp:
                all_experiences.append(exp)
                count += 1
    elif isinstance(experience_list, str):
        all_experiences = experience_list

    # organize referenves
    all_references = None
    count = 0
    if isinstance(references, list):
        all_references = []
        references.sort(key=object_precedence, reverse=True)
        for ref in references:
            if count < number_ref:
                all_references.append(ref)
                count += 1
    elif isinstance(references, str):
        all_references = references

    # organize awards
    all_awards = None
    count = 0
    if isinstance(award_section, list):
        all_awards = []
        award_section.sort(key=object_year, reverse=True)
        for award in award_section:
            if count < number_award:
                all_awards.append(award)
                count += 1
    elif isinstance(award_section, str):
        all_awards = award_section

    # organize volunteering
    all_volunteering = None
    count = 0
    if isinstance(volunteering, list):
        all_volunteering = []
        volunteering.sort(key=object_year, reverse=True)
        for vol in volunteering:
            if count < number_vol:
                all_volunteering.append(vol)
                count += 1
    elif isinstance(volunteering, str):
        all_volunteering = volunteering

    # organize hobbies
    all_hobbies = None
    count = 0
    if isinstance(hobbies, list):
        all_hobbies = []
        hobbies.sort(key=object_year, reverse=True)
        for hobby in hobbies:
            if count < number_hobbies:
                all_hobbies.append(hobby)
                count += 1
    elif isinstance(hobbies, str):
        all_hobbies = hobbies

    ###################################################################################################################
    # creating the PDF doc and formatting

    # creating filename
    file_name = posting_name + ".pdf"
    count = 0
    resume_path = "./resumes/"
    if platform.lower() == "windows":
        resume_path = '.\\Resumes\\'
    my_file = Path(resume_path + file_name)
    check = False
    # getting a new file name in case of repeats
    while not check:
        if my_file.is_file():
            count += 1
            file_name = posting_name + "(" + str(count) + ").pdf"
            my_file = Path(resume_path + file_name)
        else:
            check = True

    #c reating PDF document
    doc = SimpleDocTemplate(file_name,
                            pagesize=LETTER,
                            bottomMargin=66.0,
                            topMargin=66.0,
                            leftMargin=66.0,
                            rightMargin=66.0,
                            title="Evan Wiegers Resume",
                            subject="Evan Wiegers' Resume Builder Script",
                            author="Evan Wiegers",
                            keywords=["Resume", "Builder", "Evan", "Wiegers"])
    elements = []

    # creating paragraph styles
    # top info styles
    name_style = ParagraphStyle(name='Normal',
                                fontName='Times-Bold',
                                fontSize=22,
                                spaceAfter=6,
                                alignment=1,
                                leading=24)
    info_style = ParagraphStyle(name='Normal',
                                fontName='Times-Roman',
                                fontSize=14,
                                spaceAfter=6,
                                alignment=1)

    # Cover styles
    cover_style = ParagraphStyle(name='Normal',
                                 fontName='Times-Roman',
                                 fontSize=12,
                                 leading=16)
    re_style = ParagraphStyle(name='Normal',
                              fontName='Times-Bold',
                              fontSize=12,
                              leading=16)

    # resume section styles
    indent_style = ParagraphStyle(name='Normal',
                                  fontName='Times-Roman',
                                  fontSize=14,
                                  leftIndent=36)
    section_style = ParagraphStyle(name='Normal',
                                   fontName='Times-Bold',
                                   fontSize=18,
                                   spaceBefore=6,
                                   leading=24)
    title_style = ParagraphStyle(name='Normal',
                                 fontName='Times-Bold',
                                 fontSize=14,
                                 leading=18,
                                 spaceBefore=6)
    title_style2 = ParagraphStyle(name='Normal',
                                  fontName='Times-Bold',
                                  fontSize=14,
                                  leading=18,
                                  spaceBefore=6,
                                  spaceAfter=6)
    normal_style = ParagraphStyle(name='Normal',
                                  fontName='Times-Roman',
                                  fontSize=12,
                                  leading=18)
    bullet_style = ParagraphStyle(name='Normal',
                                  fontName='Times-Roman',
                                  fontSize=12,
                                  leading=18,
                                  bulletFontName="Times-Bold",
                                  bulletFontSize=14,
                                  leftIndent=35,
                                  bulletIndent=25)

    # extra styles
    whitespace_style = ParagraphStyle(name='Normal',
                                      fontName='Times-Bold',
                                      fontSize=12,
                                      spaceBefore=12)
    endnote_style = ParagraphStyle(name='Normal',
                                   fontName='Times-Italic',
                                   fontSize=10,
                                   leading=18,
                                   color=lightgrey)
    horizontal_line = HRFlowable(width="100%",
                                 thickness=2,
                                 lineCap='square',
                                 color=black,
                                 spaceBefore=3,
                                 spaceAfter=18,
                                 hAlign='CENTER',
                                 vAlign='BOTTOM',
                                 dash=None)

    ###################################################################################################################
    # creating a cover
    if cover:
        elements.append(Paragraph(name, name_style))
        elements.append(
            Paragraph(email + " | " + phone + " | " + address, info_style))
        elements.append(horizontal_line)

        elements.append(
            Paragraph(datetime.now().strftime("%b %d, %Y"), cover_style))

        elements.append((Paragraph("", whitespace_style)))
        elements.append(Paragraph(company, cover_style))
        elements.append(Paragraph(company_address, cover_style))

        elements.append((Paragraph("", whitespace_style)))
        elements.append(Paragraph("Re: " + posting_name, re_style))
        elements.append((Paragraph("", whitespace_style)))

        elements.append(Paragraph("Dear Sir or Madame: ", cover_style))
        elements.append((Paragraph("", whitespace_style)))

        # elements.append(Paragraph("I am keenly interested in summer employment with {0}. Please consider this as my "
        #                           "application for any position available in systems operations.".format(company),
        #                           cover_style))
        # elements.append((Paragraph("", whitespace_style)))

        elements.append(
            Paragraph(
                "I am a student at the University of Saskatchewan scheduled to graduate with a B.Sc. "
                "degree in Computer Science in spring, 2021. In 2018, I received a B.E. degree with "
                "great distinction in Chemical Engineering while finishing first in my class. In "
                "Computer Science my average to date is about 93%.",
                cover_style))
        elements.append((Paragraph("", whitespace_style)))

        elements.append(
            Paragraph(
                "I think employment with {0} would provide me with an excellent opportunity to improve "
                "my skills through challenging assignments in a demanding, professional and positive "
                "work environment. I would appreciate an opportunity to contribute to the "
                "success of {0}. I am convinced working in {0}’s challenging, innovative and "
                "professional environment would greatly enhance my skills and set me on the road "
                "to realizing my full potential.".format(company),
                cover_style))
        elements.append((Paragraph("", whitespace_style)))

        elements.append(
            Paragraph(
                "I believe I possess the required work ethic and communication skills that are "
                "necessary to contribute positively to a productive, positive and safe work "
                "environment. Further, I am highly motivated to accumulate full knowledge of my tasks "
                "to achieve the best possible performance. Over the course of my studies, I have "
                "worked with and communicated effectively in teams of people with diverse skillsets "
                "and backgrounds. I have served as project manager in my software development team "
                "and chemical engineering design projects. In that capacity, I have been exposed to "
                "many software programs while coordinating our teams’ action plans and the production "
                "of reports, memoranda, and presentations. At a previous internship, I systematically "
                "studied the company database beyond the requirements of my role to better understand "
                "how my work could improve business operations.", cover_style))
        elements.append((Paragraph("", whitespace_style)))

        elements.append(
            Paragraph(
                "Attached is my resume. I hope to have an opportunity to discuss my application in "
                "greater detail with you. I may be contacted by phone at {0} or by email at "
                "{1}".format(phone, email), cover_style))
        elements.append((Paragraph("", whitespace_style)))

        elements.append(
            Paragraph("I greatly appreciate your consideration.", cover_style))
        elements.append((Paragraph("", whitespace_style)))
        #elements.append((Paragraph("", whitespace_style)))
        elements.append(Paragraph("Evan Wiegers", cover_style))

        #now on to the resume
        elements.append(PageBreak())

    ###################################################################################################################
    # Now for actually building the resume

    # add the contact info section to PDF
    elements.append(Paragraph(name, name_style))
    elements.append(Paragraph(email + " | " + github_account, info_style))
    elements.append(Paragraph(phone + " | " + address, info_style))
    elements.append(horizontal_line)

    # add education section to PDF
    if all_education != (None or []):
        elements.append(Paragraph("EDUCATION", section_style))
        elements.append(horizontal_line)
        if isinstance(all_education, list):
            for educ in all_education:
                elements.append(
                    Paragraph(educ.get_name() + " | " + educ.get_institution(),
                              title_style))
                descript = educ.get_degree_title() + " | " + educ.get_grade(
                ) + " | " + educ.get_length()
                if not educ.get_is_finished():
                    descript += " (Expected)"
                elements.append(Paragraph(descript, indent_style))
        elif isinstance(all_education, str):
            elements.append(Paragraph(all_education, indent_style))

    # add skill section to PDF
    if all_skills != (None or []):
        elements.append(Paragraph("", whitespace_style))
        elements.append(Paragraph("RELEVENT SKILLS", section_style))
        elements.append(horizontal_line)
        if isinstance(all_skills, SkillSection):
            if all_skills.get_language() != (None or []):
                elements.append(
                    Paragraph("Languages and Proficiencies", title_style2))
                for skill in all_skills.get_language():
                    elements.append(
                        Paragraph(
                            "<bullet>&bull</bullet>" + skill.get_description(),
                            bullet_style))
            if all_skills.get_technical() != (None or []):
                elements.append(Paragraph("Technical and Design",
                                          title_style2))
                for skill in all_skills.get_technical():
                    elements.append(
                        Paragraph(
                            "<bullet>&bull</bullet>" + skill.get_description(),
                            bullet_style))
            if all_skills.get_interpersonal() != (None or []):
                elements.append(Paragraph("Interpersonal", title_style2))
                for skill in all_skills.get_interpersonal():
                    elements.append(
                        Paragraph(
                            "<bullet>&bull</bullet>" + skill.get_description(),
                            bullet_style))
            if all_skills.get_other() != (None or []):
                elements.append(Paragraph("Other", title_style2))
                for skill in all_skills.get_other():
                    elements.append(
                        Paragraph(
                            "<bullet>&bull</bullet>" + skill.get_description(),
                            bullet_style))
        elif isinstance(all_skills, list):
            for skill in all_skills:
                elements.append(
                    Paragraph(
                        "<bullet>&bull</bullet>" + skill.get_description(),
                        bullet_style))
        elif isinstance(all_skills, str):
            elements.append(Paragraph(all_skills, normal_style))

    # new page
    elements.append(PageBreak())
    header = "Evan Wiegers (306) 540-7573 /2"

    # add experience section
    if all_experiences != (None or []):
        elements.append(Paragraph("RECENT EXPERIENCE", section_style))
        elements.append(horizontal_line)
        if isinstance(all_experiences, list):
            for exp in all_experiences:
                elements.append(
                    Paragraph(
                        exp.get_name() + "                            " +
                        exp.get_length(), title_style))
                elements.append(
                    Paragraph(
                        exp.get_institution() + ", " + exp.get_location(),
                        normal_style))
                elements.append(
                    Paragraph("<bullet>&bull</bullet>" + exp.get_description(),
                              bullet_style))
        elif isinstance(all_experiences, str):
            elements.append(Paragraph(all_experiences, normal_style))

    # add awards section
    if all_awards != (None or []):
        elements.append(Paragraph("", whitespace_style))
        elements.append(Paragraph("ACADEMIC HONOURS", section_style))
        elements.append(horizontal_line)
        if isinstance(all_awards, list):
            for award in all_awards:
                elements.append(
                    Paragraph(
                        "<bullet>&bull</bullet>" + award.get_name() + ",  " +
                        award.get_year(), bullet_style))
        elif isinstance(all_awards, str):
            elements.append(Paragraph(all_awards, normal_style))

    # add volunteering section
    if all_volunteering != (None or []):
        elements.append(Paragraph("", whitespace_style))
        elements.append(Paragraph("VOLUNTEERING", section_style))
        elements.append(horizontal_line)
        if isinstance(all_volunteering, list):
            for vol in all_volunteering:
                elements.append(
                    Paragraph(
                        "<bullet>&bull</bullet>" + vol.get_description() +
                        ",  " + vol.get_year(), bullet_style))
        elif isinstance(all_volunteering, str):
            elements.append(Paragraph(all_volunteering, normal_style))

    # add hobby section
    if all_hobbies != (None or []):
        elements.append(Paragraph("", whitespace_style))
        elements.append(Paragraph("HOBBIES", section_style))
        elements.append(horizontal_line)
        if isinstance(all_hobbies, list):
            elements.append(
                Paragraph("<bullet>&bull</bullet>" + ', '.join(all_hobbies),
                          bullet_style))
        elif isinstance(all_hobbies, str):
            elements.append(Paragraph(all_hobbies, normal_style))

    # add reference section
    if all_references != (None or []):
        elements.append(Paragraph("", whitespace_style))
        elements.append(Paragraph("REFERENCES", section_style))
        elements.append(horizontal_line)
        if isinstance(all_references, list):
            for ref in all_references:
                elements.append(Paragraph(ref.get_name(), title_style))
                elements.append(
                    Paragraph(ref.get_title() + ", " + ref.get_location(),
                              normal_style))
                elements.append(
                    Paragraph(ref.get_phone() + " or " + ref.get_email(),
                              normal_style))
        elif isinstance(all_references, str):
            elements.append(Paragraph(all_references, normal_style))

    #add endnote
    elements.append(Paragraph("", whitespace_style))
    elements.append(
        Paragraph(
            "This resume was created entirely with a Python script made by Evan Wiegers",
            endnote_style))

    # building PDF and moving it to appropriate directory
    doc.build(elements)
    shutil.move(file_name, "./resumes")

    return
示例#5
0
    def cevirPDF(self):
        for j in range(0,4):
            self.dersAdi = ""
            self.listSoru = []
            self.listA = []
            self.listB = []
            self.listC = []
            self.listD = []
            self.listE = []


            if j==0:
                self.kTürü='A'
            elif j==1:
                self.kTürü='B'
            elif j==2:
                self.kTürü='C'
            elif j==3:
                self.kTürü='D'
            Elements = []
            dAdi = 'Oturum-'+self.kTürü+'.pdf'
            doc = BaseDocTemplate(dAdi, showBoundary=0)

            for t in range(0,len(self.filesPath)):

                self.gExcel = pandas.read_excel(io=self.filesPath[t], parse_cols=2, index_col=2, sheetname=j)
                for i in range(0, 25):
                    self.listSoru.append(self.gExcel.index[i])
                self.gExcel = pandas.read_excel(io=self.filesPath[t], parse_cols=10, index_col=10, sheetname=j)
                for i in range(0, 25):
                    self.listA.append(self.gExcel.index[i])
                self.gExcel = pandas.read_excel(io=self.filesPath[t], parse_cols=11, index_col=11, sheetname=j)
                for i in range(0, 25):
                    self.listB.append(self.gExcel.index[i])
                self.gExcel = pandas.read_excel(io=self.filesPath[t], parse_cols=12, index_col=12, sheetname=j)
                for i in range(0, 25):
                    self.listC.append(self.gExcel.index[i])
                self.gExcel = pandas.read_excel(io=self.filesPath[t], parse_cols=13, index_col=13, sheetname=j)
                for i in range(0, 25):
                    self.listD.append(self.gExcel.index[i])
                self.gExcel = pandas.read_excel(io=self.filesPath[t], parse_cols=14, index_col=14, sheetname=j)
                for i in range(0, 25):
                    self.listE.append(self.gExcel.index[i])
                self.gExcel = pandas.read_excel(io=self.filesPath[t], parse_cols=28, index_col=28, sheetname=j)
                self.dersAdi = self.gExcel.index[0]
                self.gExcel = pandas.read_excel(io=self.filesPath[t], parse_cols=27, index_col=27, sheetname=j)
                self.dersAdik = self.gExcel.index[0]
                for i in range(0, 25):
                    self.listSoru[i] = self.listSoru[i].replace('\n', '<br />\n')

                print("Excelden çekildi.")


                styles = getSampleStyleSheet()
                pdfmetrics.registerFont(TTFont('Arial', 'Arial.ttf'))
                pdfmetrics.registerFont(TTFont('ArialBd', 'ArialBd.ttf'))

                # Baslık icin yazı ayarlarını yaptık
                titleStyle = styles["Title"]
                titleStyle.fontSize = 16
                titleStyle.fontName = 'ArialBd'
                titleStyle.leading = 65

                #Soru için font
                arStyle = styles["Heading1"]
                arStyle.fontSize = 10
                arStyle.fontName = 'ArialBd'
                arStyle.leading = 11
                arStyle.alignment = TA_JUSTIFY


                # Paragraflar için yazı tipini ayarladık
                parStyle = styles["Normal"]
                parStyle.fontSize = 10
                parStyle.fontName = 'Arial'
                parStyle.leading = 16
                #parStyle.alignment = TA_LEFT

                # Acıklama için yazı tipini ayarladık
                parStyle2 = styles["Normal"]
                parStyle2.fontSize = 10
                parStyle2.fontName = 'Arial'
                parStyle2.leading = 16
                parStyle2.alignment = TA_JUSTIFY

                # column için ölçüleri oluşturduk
                frameHeight = doc.height + 2 * inch
                firstPageHeight = 6 * inch
                firstPageBottom = frameHeight - firstPageHeight

                # Baslık frame'i
                frameT = Frame(2.7 * cm, firstPageBottom, doc.width, firstPageHeight)

                # Two column - burda oluşturduk
                frame1 = Frame(2.7 * cm,2.7 * cm,7.5 * cm,23.3 * cm, id='col1')
                frame2 = Frame(11.6 * cm,2.7 * cm,7.5 * cm,23.3 * cm, id='col2')

                Elements.append(Paragraph('<br />\n'+self.dersAdi, titleStyle))
                Elements.append(NextPageTemplate('TwoCol'))
                Elements.append(FrameBreak())

                for i in range(0, 25):
                    if i != 24:
                        index = self.listSoru[i].rfind("\n")
                        imagel=self.listSoru[i].find("&")
                        image2 = self.listSoru[i].rfind("&")
                        if imagel == -1 or image2 == -1:
                            if index == -1:
                                ptext = '<font fontSize=10 fontName=ArialBd>%s.&nbsp;&nbsp;</font>' % str(i+1)
                                pptext = ptext+self.listSoru[i]
                                Soru = Paragraph(pptext, arStyle)
                                Bosluk = Spacer(1, 0.3 * cm)
                                A = Paragraph('A)&nbsp;&nbsp;' + str(self.listA[i]), parStyle)
                                B = Paragraph('B)&nbsp;&nbsp;' + str(self.listB[i]), parStyle)
                                C = Paragraph('C)&nbsp;&nbsp;' + str(self.listC[i]), parStyle)
                                D = Paragraph('D)&nbsp;&nbsp;' + str(self.listD[i]), parStyle)
                                E = Paragraph('E)&nbsp;&nbsp;' + str(self.listE[i]), parStyle)
                                Bosluk2 = Spacer(1, self.bMiktari * cm)
                                Elements.append(KeepTogether([Soru, Bosluk, A, B, C, D, E, Bosluk2]))
                            else:
                                soru1 = self.listSoru[i][0:index]
                                soru2 = self.listSoru[i][index:]
                                ptext = '<font fontSize=10 fontName=ArialBd>%s.&nbsp;&nbsp;</font>' % str(i + 1)
                                pptext = ptext + soru1
                                Soruy1 = Paragraph(pptext, parStyle2)
                                Soruy2 = Paragraph(soru2,arStyle)
                                Bosluk = Spacer(1, 0.3 * cm)
                                A = Paragraph('A)&nbsp;&nbsp;' + str(self.listA[i]), parStyle)
                                B = Paragraph('B)&nbsp;&nbsp;' + str(self.listB[i]), parStyle)
                                C = Paragraph('C)&nbsp;&nbsp;' + str(self.listC[i]), parStyle)
                                D = Paragraph('D)&nbsp;&nbsp;' + str(self.listD[i]), parStyle)
                                E = Paragraph('E)&nbsp;&nbsp;' + str(self.listE[i]), parStyle)
                                Bosluk2 = Spacer(1, self.bMiktari * cm)
                                Elements.append(KeepTogether([Soruy1,Soruy2, Bosluk, A, B, C, D, E, Bosluk2]))
                        else:
                            imageAd=self.listSoru[i][imagel+1:image2]
                            imageK=self.listSoru[i][imagel:image2+1]
                            soru1 = self.listSoru[i][0:index]
                            soruBas = soru1[0:imagel]
                            soruSon = soru1[image2+1:]
                            soru2 = self.listSoru[i][index:]
                            imagePath="C:\Image\\" + imageAd
                            im = Image(imagePath,7.5 * cm, 5*cm)
                            ySoru = self.listSoru[i]
                            yySoru = ySoru.replace(imageK,"")
                            if index == -1:
                                ptext = Paragraph(str(i+1)+".&nbsp;&nbsp;",arStyle)
                                Soru = Paragraph(yySoru, arStyle)
                                Bosluk = Spacer(1, 0.3 * cm)
                                A = Paragraph('A)&nbsp;&nbsp;' + str(self.listA[i]), parStyle)
                                B = Paragraph('B)&nbsp;&nbsp;' + str(self.listB[i]), parStyle)
                                C = Paragraph('C)&nbsp;&nbsp;' + str(self.listC[i]), parStyle)
                                D = Paragraph('D)&nbsp;&nbsp;' + str(self.listD[i]), parStyle)
                                E = Paragraph('E)&nbsp;&nbsp;' + str(self.listE[i]), parStyle)
                                Bosluk2 = Spacer(1, self.bMiktari * cm)
                                Elements.append(KeepTogether([ptext,im,Soru, Bosluk, A, B, C, D, E, Bosluk2]))
                            else:

                                ptext = '<font fontSize=10 fontName=ArialBd>%s.&nbsp;&nbsp;</font>' % str(i + 1)
                                pptext = ptext + soruBas
                                soruy1Bas = Paragraph(pptext, parStyle2)
                                soruy1Son = Paragraph(soruSon,parStyle2)
                                Soruy2 = Paragraph(soru2,arStyle)
                                Bosluk = Spacer(1, 0.3 * cm)
                                A = Paragraph('A)&nbsp;&nbsp;' + str(self.listA[i]), parStyle)
                                B = Paragraph('B)&nbsp;&nbsp;' + str(self.listB[i]), parStyle)
                                C = Paragraph('C)&nbsp;&nbsp;' + str(self.listC[i]), parStyle)
                                D = Paragraph('D)&nbsp;&nbsp;' + str(self.listD[i]), parStyle)
                                E = Paragraph('E)&nbsp;&nbsp;' + str(self.listE[i]), parStyle)
                                Bosluk2 = Spacer(1, self.bMiktari * cm)
                                Elements.append(KeepTogether([soruy1Bas,im,soruy1Son,Soruy2, Bosluk, A, B, C, D, E, Bosluk2]))
                    else:
                        index = self.listSoru[i].rfind("\n")
                        imagel = self.listSoru[i].find("&")
                        image2 = self.listSoru[i].rfind("&")
                        if imagel == -1 or image2 == -1:
                            if index == -1:
                                ptext = '<font fontSize=10 fontName=ArialBd>%s.&nbsp;&nbsp;</font>' % str(i + 1)
                                pptext = ptext + self.listSoru[i]
                                Soru = Paragraph(pptext, arStyle)
                                Bosluk = Spacer(1, 0.3 * cm)
                                A = Paragraph('A)&nbsp;&nbsp;' + str(self.listA[i]), parStyle)
                                B = Paragraph('B)&nbsp;&nbsp;' + str(self.listB[i]), parStyle)
                                C = Paragraph('C)&nbsp;&nbsp;' + str(self.listC[i]), parStyle)
                                D = Paragraph('D)&nbsp;&nbsp;' + str(self.listD[i]), parStyle)
                                E = Paragraph('E)&nbsp;&nbsp;' + str(self.listE[i]), parStyle)
                                Bosluk2 = Spacer(1, self.bMiktari * cm)
                                tBitti = Paragraph(self.dersAdi + ' TESTİ BİTTİ.', arStyle)
                                Elements.append(KeepTogether([Soru, Bosluk, A, B, C, D, E, Bosluk2,tBitti]))

                            else:
                                soru1 = self.listSoru[i][0:index]
                                soru2 = self.listSoru[i][index:]
                                ptext = '<font fontSize=10 fontName=ArialBd>%s.&nbsp;&nbsp;</font>' % str(i + 1)
                                pptext = ptext + soru1
                                Soruy1 = Paragraph(pptext, parStyle2)
                                Soruy2 = Paragraph(soru2, arStyle)
                                Bosluk = Spacer(1, 0.3 * cm)
                                A = Paragraph('A)&nbsp;&nbsp;' + str(self.listA[i]), parStyle)
                                B = Paragraph('B)&nbsp;&nbsp;' + str(self.listB[i]), parStyle)
                                C = Paragraph('C)&nbsp;&nbsp;' + str(self.listC[i]), parStyle)
                                D = Paragraph('D)&nbsp;&nbsp;' + str(self.listD[i]), parStyle)
                                E = Paragraph('E)&nbsp;&nbsp;' + str(self.listE[i]), parStyle)
                                Bosluk2 = Spacer(1, self.bMiktari * cm)
                                tBitti = Paragraph(self.dersAdi + ' TESTİ BİTTİ.', arStyle)
                                Elements.append(KeepTogether([Soruy1, Soruy2, Bosluk, A, B, C, D, E, Bosluk2,tBitti]))

                        else:
                            imageAd = self.listSoru[i][imagel + 1:image2]
                            imageK = self.listSoru[i][imagel:image2 + 1]
                            soru1 = self.listSoru[i][0:index]
                            soruBas = soru1[0:imagel]
                            soruSon = soru1[image2 + 1:]
                            soru2 = self.listSoru[i][index:]
                            imagePath = "D:\İçerikler\Python\ExcelToWord\Image\\" + imageAd
                            im = Image(imagePath, 7.5 * cm, 5 * cm)
                            ySoru = self.listSoru[i]
                            yySoru = ySoru.replace(imageK, "")
                            if index == -1:
                                ptext = Paragraph(str(i + 1) + ".&nbsp;&nbsp;", arStyle)
                                Soru = Paragraph(yySoru, arStyle)
                                Bosluk = Spacer(1, 0.3 * cm)
                                A = Paragraph('A)&nbsp;&nbsp;' + str(self.listA[i]), parStyle)
                                B = Paragraph('B)&nbsp;&nbsp;' + str(self.listB[i]), parStyle)
                                C = Paragraph('C)&nbsp;&nbsp;' + str(self.listC[i]), parStyle)
                                D = Paragraph('D)&nbsp;&nbsp;' + str(self.listD[i]), parStyle)
                                E = Paragraph('E)&nbsp;&nbsp;' + str(self.listE[i]), parStyle)
                                Bosluk2 = Spacer(1, self.bMiktari * cm)
                                tBitti = Paragraph(self.dersAdi + ' TESTİ BİTTİ.', arStyle)
                                Elements.append(KeepTogether([ptext, im, Soru, Bosluk, A, B, C, D, E, Bosluk2,tBitti]))

                            else:

                                ptext = '<font fontSize=10 fontName=ArialBd>%s.&nbsp;&nbsp;</font>' % str(i + 1)
                                pptext = ptext + soruBas
                                soruy1Bas = Paragraph(pptext, parStyle2)
                                soruy1Son = Paragraph(soruSon, parStyle2)
                                Soruy2 = Paragraph(soru2, arStyle)
                                Bosluk = Spacer(1, 0.3 * cm)
                                A = Paragraph('A)&nbsp;&nbsp;' + str(self.listA[i]), parStyle)
                                B = Paragraph('B)&nbsp;&nbsp;' + str(self.listB[i]), parStyle)
                                C = Paragraph('C)&nbsp;&nbsp;' + str(self.listC[i]), parStyle)
                                D = Paragraph('D)&nbsp;&nbsp;' + str(self.listD[i]), parStyle)
                                E = Paragraph('E)&nbsp;&nbsp;' + str(self.listE[i]), parStyle)
                                Bosluk2 = Spacer(1, self.bMiktari * cm)
                                tBitti = Paragraph(self.dersAdi+' TESTİ BİTTİ.',arStyle)
                                Elements.append(KeepTogether([soruy1Bas, im, soruy1Son, Soruy2, Bosluk, A, B, C, D, E, Bosluk2,tBitti]))


                Elements.append(NextPageTemplate('Title'))
                Elements.append(PageBreak())

                doc.addPageTemplates([PageTemplate(id='Title', frames=[frameT, frame1, frame2], onPage=self.addPageNumber),
                                      PageTemplate(id='TwoCol', frames=[frame1, frame2], onPage=self.addPageNumber), ])

                self.listSoru.clear()
                self.listA.clear()
                self.listB.clear()
                self.listC.clear()
                self.listD.clear()
                self.listE.clear()

            doc.build(Elements)

            print("PDF'e çevrildi.")
        paragraph_10 = Paragraph(str(rows.Author), sample_style_sheet['TestStyle'])
        paragraph_11 = Paragraph("Summary of Article", sample_style_sheet['Heading2'])
        paragraph_12 = Paragraph(summarize(), sample_style_sheet['TestStyle'])
        paragraph_13 = Paragraph("Sentiment", sample_style_sheet['Heading2'])
        paragraph_14 = Paragraph(sentiment, sample_style_sheet['TestStyle'])
        paragraph_15 = Paragraph("Content", sample_style_sheet['Heading2'])
        paragraph_16 = Paragraph(rows.Article, sample_style_sheet['TestStyle'])


        # appending all the paragraphs to the flowables
        flowables.append(paragraph_1)
        flowables.append(paragraph_2)
        flowables.append(paragraph_3)
        flowables.append(paragraph_4)
        flowables.append(paragraph_5)
        flowables.append(paragraph_6)
        flowables.append(paragraph_7)
        flowables.append(paragraph_8)
        flowables.append(paragraph_9)
        flowables.append(paragraph_10)
        flowables.append(paragraph_11)
        flowables.append(paragraph_12)
        flowables.append(paragraph_13)
        flowables.append(paragraph_14)
        flowables.append(paragraph_15)
        flowables.append(paragraph_16)
        flowables.append(PageBreak())  # Next page after one article has been printed on document

my_doc.build(flowables)  # building the pdf document from the flowables list
#os.remove('news.csv')
示例#7
0
    def create_pdf(self):

        body = []

        RptColNames = []
        RptColWdths = []

        styles = getSampleStyleSheet()
        spacer1 = Spacer(0, 0.25 * inch)
        spacer2 = Spacer(0, 0.5 * inch)

        tblstyle = TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25,
                                colors.black),
                               ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
                               ('LEFTPADDING', (0, 0), (-1, -1), 5),
                               ('RIGHTPADDING', (0, 0), (-1, -1), 5),
                               ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                               ('VALIGN', (0, 0), (-1, -1), 'MIDDLE')])

        n = 0
        for tblname in self.rpttbl:
            for tbl_data in self.rptdata[n]:
                self.num_records = len(self.rptdata[n])
                # Allow for specified number of rows
                # of data per page this means the number
                # of pages is just the number or recordes
                # divided by number of rows_page
                if self.num_records % self.Rows_Pg == 0:
                    NoPgs = (self.num_records // self.Rows_Pg) * 2
                else:
                    NoPgs = (self.num_records // self.Rows_Pg + 1) * 2

                sect_pg = int(
                    round(round(len(tbl_data) / self.Colms_pg, 1) + .1))

                # build the report one page at a time based on even
                # and odd number pages starting at page 1
            for page in range(1, NoPgs + 1, sect_pg):
                # provide the table name for the page header on each page
                ptext = '<font size=14>%s</font>' % self.ttl[n]
                body.append(Paragraph(ptext, styles["Heading2"]))

                line = LineDrw(500)

                body.append(line)
                body.append(spacer1)
                for m in range(1, sect_pg + 1):
                    start = (m - 1) * self.Colms_pg
                    finish = m * self.Colms_pg

                    RptColNames = self.columnames[n][start:finish]
                    RptColWdths = [
                        i * self.textAdjust
                        for i in self.colms[n][start:finish]
                    ]

                    if start != 0:
                        RptColNames.insert(0, self.columnames[n][0])
                        RptColWdths.insert(0,
                                           self.colms[n][0] * self.textAdjust)

                    tbldata = self.tbldata(styles, start, finish, page, n)
                    tbldata.insert(0, tuple(RptColNames))
                    tbl = Table(tbldata, colWidths=RptColWdths)

                    tbl.setStyle(tblstyle)
                    body.append(spacer2)

                    body.append(tbl)
                body.append(PageBreak())

            n += 1

        for nodata in self.exclud:
            txt = (' '.join(re.findall('([A-Z][a-z]*)', nodata)))
            txt += 's have not been set up.'

            ptext = '<font size=14>%s</font>' % txt
            body.append(Paragraph(ptext, styles["Heading2"]))

            line = LineDrw(500)

            body.append(line)
            body.append(spacer1)

        doc = SimpleDocTemplate('tmp_rot_file.pdf',
                                pagesize=landscape(letter),
                                rightMargin=.5 * inch,
                                leftMargin=.5 * inch,
                                topMargin=.75 * inch,
                                bottomMargin=.5 * inch)

        doc.build(body)

        pdf_old = open('tmp_rot_file.pdf', 'rb')
        pdf_reader = PyPDF4.PdfFileReader(pdf_old)
        pdf_writer = PyPDF4.PdfFileWriter()

        for pagenum in range(pdf_reader.numPages):
            page = pdf_reader.getPage(pagenum)
            page.rotateCounterClockwise(90)
            pdf_writer.addPage(page)

        pdf_out = open(self.filename, 'wb')
        pdf_writer.write(pdf_out)
        pdf_out.close()
        pdf_old.close()
        os.remove('tmp_rot_file.pdf')
示例#8
0
def generate_pdf_center_list(filename, stations, gender):
    """Write station list for a given center/gender combination.

    All stations must be for the same center.

    Return the number of pages in the PDF.
    """
    # All stations must have the same center.
    center = stations[0].center
    center_id = center.center_id
    assert (all(
        [station.center.center_id == center_id for station in stations]))

    # set styles
    styles = getArabicStyle()

    # get strings
    gender_string = STRINGS[GENDER_NAMES[gender]]
    cover_string = STRINGS['ed_center_list_cover']
    header_string = STRINGS['ed_center_list_header']

    # cover page
    center_name = reshape(center.name)

    template = u'%s: %s / %s'
    subconstituency_name = reshape(center.subconstituency.name_arabic)
    params = (STRINGS['subconstituency_name'], center.subconstituency.id,
              subconstituency_name)
    subconstituency = template % params
    center_info = {
        'gender':
        u'%s: %s' % (STRINGS['gender'], gender_string),
        'number':
        u'%s: %d' % (STRINGS['center_number'], center_id),
        'name':
        u'%s: %s' % (STRINGS['center_name'], center_name),
        'name_trunc':
        u'%s: %s' %
        (STRINGS['center_name'], truncate_center_name(center_name)),
        'subconstituency':
        subconstituency,
        'copy_info':
        build_copy_info(center),
    }

    # create document
    doc = CountingDocTemplate(filename,
                              pagesize=A4,
                              topMargin=1 * cm,
                              bottomMargin=1 * cm,
                              leftMargin=1.5 * cm,
                              rightMargin=2.54 * cm)

    # elements, cover page first
    elements = [
        Image(hnec_logo(), width=10 * cm, height=2.55 * cm),
        Spacer(48, 48),
        Paragraph(cover_string, styles['Title']),
        Spacer(18, 18),
        Paragraph(center_info['gender'], styles['CoverInfo-Bold']),
        Paragraph(center_info['number'], styles['CoverInfo']),
        Paragraph(center_info['name'], styles['CoverInfo']),
        Paragraph(center_info['copy_info'], styles['CoverInfo']),
        Paragraph(center_info['subconstituency'], styles['CoverInfo']),
        PageBreak(),
    ]

    roll = []
    for station in stations:
        if station.gender == gender:
            roll.extend(station.roll)
        else:
            # Coverage can't "see" the next line executed.
            continue  # pragma: no cover

        skipped_voters = []  # to re-add when we go over a page break
        unisex = False

        for page in chunker(
                station.roll,
                settings.ROLLGEN_REGISTRATIONS_PER_PAGE_POLLING_LIST):
            # table header
            data = [[
                STRINGS['station_header'], STRINGS['the_names'],
                STRINGS['number']
            ]]

            # hacks for simulating page break between genders in unisex stations
            # last_voter tracks the previous iteration's last voter so we can add a blank line
            # at the switch
            last_voter = None
            voter_count = 0

            for voter in page:
                # if unisex station, add pagebreak between genders
                if (station.gender == UNISEX) and last_voter and \
                   (voter.gender != last_voter.gender):

                    # simulate a page break by adding N blank lines where
                    # N = ROLLGEN_REGISTRATIONS_PER_PAGE_POLLING_LIST - voter_count
                    logger.debug("voter_count={}".format(voter_count))
                    lines_left = settings.ROLLGEN_REGISTRATIONS_PER_PAGE_POLLING_LIST - voter_count
                    logger.debug("lines_left={}".format(lines_left))
                    if not unisex:
                        for i in range(0, lines_left):
                            data.append([])
                    unisex = True
                    skipped_voters = page[voter_count:voter_count + lines_left]
                    log_voters("skipping", skipped_voters)
                    break
                if not unisex:
                    data.append([
                        station.number,
                        reshape(format_name(voter)), voter.registrant_number
                    ])
                else:
                    skipped_voters.append(page[voter_count])
                last_voter = voter
                voter_count += 1

            if len(data) > 1:
                draw_header(elements, header_string, center_info, styles,
                            station, "list")
                draw_body(elements, data,
                          settings.ROLLGEN_REGISTRATIONS_PER_PAGE_POLLING_LIST)
                draw_footer(elements, gender_string, styles)

        if skipped_voters:
            data = [[
                STRINGS['station_header'], STRINGS['the_names'],
                STRINGS['number']
            ]]

            for voter in skipped_voters:
                data.append([
                    station.number,
                    reshape(format_name(voter)), voter.registrant_number
                ])
            log_voters("re-adding", skipped_voters)
            draw_header(elements, header_string, center_info, styles, station,
                        "list")
            draw_body(elements, data,
                      settings.ROLLGEN_REGISTRATIONS_PER_PAGE_POLLING_LIST)
            draw_footer(elements, gender_string, styles)

    with out_of_disk_space_handler_context():
        doc.build(elements,
                  canvasmaker=NumberedCanvas,
                  onLaterPages=drawHnecLogo)

    return doc.n_pages
示例#9
0
 def report_pages(self, reports: list):
     pages = []
     for report in reports:
         pages.extend(self.report_page(report))
         pages.append(PageBreak())
     return pages
示例#10
0
def generate_pdf_station_sign(filename, station):
    """Write a sign for the given station to filename.

    Return the number of pages in the PDF (which is always 1 if things are working properly).
    """
    # set styles
    styles = getArabicStyle()

    # get strings
    gender_string = STRINGS[GENDER_NAMES[station.gender]]
    cover_string = STRINGS['ed_polling_sign_header']

    # cover page
    center_name = reshape(station.center.name)
    if station.gender == UNISEX:
        # Unisex centers have a couple of lines of extra info at the bottom, and if the center
        # name happens to be long enough to wrap to a new line, the sign will wrap to two pages.
        # We truncate the center name to avoid that.
        center_name = truncate_center_name(center_name)

    center_info = {
        'gender': '%s: %s' % (STRINGS['gender'], gender_string),
        'number':
        '%s: %d' % (STRINGS['center_number'], station.center.center_id),
        'name': '%s: %s' % (STRINGS['center_name'], center_name),
        'copy_info': build_copy_info(station.center),
    }
    station_info = "%s &nbsp;&nbsp; %d" % (STRINGS['station_number'],
                                           station.number)

    # name range table
    name_range_data = station_name_range(station)
    style = styles['NameRangeTableCell']
    name_range_data = [[Paragraph(cell, style) for cell in row]
                       for row in name_range_data]
    # Table params:          data             column_widths            row_height
    name_range_table = Table(name_range_data, [11 * cm, 2.4 * cm, 2.4 * cm],
                             1.1 * cm)

    # create landscape docuemnt
    doc = CountingDocTemplate(filename,
                              pagesize=landscape(A4),
                              topMargin=1 * cm,
                              bottomMargin=1 * cm)

    # all elements on single page
    elements = [
        Table([[
            Image(cda_logo(), width=1.71 * cm, height=1.3 * cm), '',
            Image(hnec_logo(), width=4 * cm, height=1.3 * cm)
        ]], [4 * cm, 10 * cm, 4 * cm], 2 * cm),
        Spacer(30, 30),
        Paragraph(cover_string, styles['Title']),
        Spacer(12, 12),
        Paragraph(center_info['name'], styles['Title']),
        Spacer(12, 12),
        Paragraph(center_info['number'], styles['Title']),
        Spacer(12, 12),
        Paragraph(center_info['copy_info'], styles['TitleCopyInfo']),
        Spacer(12, 12),
        Paragraph(station_info, styles['SignStationNumber']),
        Spacer(56, 56),
        Paragraph(center_info['gender'], styles['Title']),
        Spacer(10, 10),
        Paragraph(STRINGS['names_range'], styles['SignNameRange']),
        name_range_table,
        PageBreak(),
    ]

    with out_of_disk_space_handler_context():
        doc.build(elements)

    return doc.n_pages
示例#11
0
def generate_pdf_station_book(filename, station):
    """Write the registration book for the given station to filename.

    If station gender is unisex, adds page breaks between male and female

    Return the number of pages in the PDF.
    """
    center = station.center

    # set styles
    styles = getArabicStyle()

    # get strings
    gender_string = STRINGS[GENDER_NAMES[station.gender]]
    cover_string = STRINGS['ed_station_book_cover']
    header_string = STRINGS['ed_station_book_header']

    # cover page
    center_name = reshape(center.name)
    template = u'%s: %s / %s'
    subconstituency_name = reshape(center.subconstituency.name_arabic)
    params = (STRINGS['subconstituency_name'], center.subconstituency.id,
              subconstituency_name)
    subconstituency = template % params

    center_info = {
        'gender':
        u'%s: %s' % (STRINGS['gender'], gender_string),
        'number':
        u'%s: %d' % (STRINGS['center_number'], center.center_id),
        'name':
        u'%s: %s' % (STRINGS['center_name'], center_name),
        'name_trunc':
        u'%s: %s' %
        (STRINGS['center_name'], truncate_center_name(center_name)),
        'subconstituency':
        subconstituency,
        'copy_info':
        build_copy_info(center),
    }

    station_info = "%s &nbsp;&nbsp; %d" % (STRINGS['station_number'],
                                           station.number)

    # name range table for cover
    name_range_data = station_name_range(station)
    style = styles['NameRangeTableCell']
    name_range_data = [[Paragraph(cell, style) for cell in row]
                       for row in name_range_data]
    # Table params:          data             column_widths            row_height
    name_range_table = Table(name_range_data, [11 * cm, 2.4 * cm, 2.4 * cm],
                             1.5 * cm)

    # create document
    doc = CountingDocTemplate(filename,
                              pagesize=A4,
                              topMargin=1 * cm,
                              bottomMargin=1 * cm,
                              leftMargin=1.5 * cm,
                              rightMargin=2.54 * cm)
    # elements, cover page first
    elements = [
        Image(hnec_logo(), width=10 * cm, height=2.55 * cm),
        Spacer(48, 48),
        Paragraph(cover_string, styles['Title']),
        Spacer(18, 18),
        Paragraph(center_info['gender'], styles['CoverInfo-Bold']),
        Paragraph(center_info['number'], styles['CoverInfo']),
        Paragraph(center_info['name'], styles['CoverInfo']),
        Paragraph(center_info['copy_info'], styles['CoverInfo']),
        Paragraph(center_info['subconstituency'], styles['CoverInfo']),
        Spacer(18, 18),
        Paragraph(station_info, styles['CoverStationNumber']),
        Spacer(60, 60),
        Paragraph(STRINGS['names_range'], styles['CoverNameRange']),
        Spacer(18, 18),
        name_range_table,
        PageBreak(),
    ]

    # skipped_voters holds voters that we need to re-add when we go over a page break
    skipped_voters = []
    unisex = False

    for page in chunker(station.roll,
                        settings.ROLLGEN_REGISTRATIONS_PER_PAGE_POLLING_BOOK):
        data = [[STRINGS['voted'], STRINGS['the_names'],
                 STRINGS['number']]]  # table header

        # hacks for simulating page break between genders in unisex stations
        # last_voter tracks the previous iteration's last voter so we can add a blank line
        # at the switch
        voter_count = 0
        last_voter = None

        for voter in page:
            # if unisex station, add pagebreak between genders

            if (station.gender == UNISEX) and last_voter and \
               (voter.gender != last_voter.gender):

                # simulate a page break by adding n_registrants_per_page - voter_count blank lines
                logger.debug("voter_count={}".format(voter_count))
                lines_left = settings.ROLLGEN_REGISTRATIONS_PER_PAGE_POLLING_BOOK - voter_count
                logger.debug("lines_left={}".format(lines_left))
                if not unisex:
                    for i in range(0, lines_left):
                        data.append([])
                unisex = True
                skipped_voters = page[voter_count:voter_count + lines_left]
                log_voters("skipping", skipped_voters)
                break
            if not unisex:
                data.append(
                    ['',
                     reshape(format_name(voter)), voter.registrant_number])
            else:
                skipped_voters.append(page[voter_count])
            last_voter = voter
            voter_count += 1

        if len(data) > 1:
            draw_header(elements, header_string, center_info, styles, station,
                        "book")
            draw_body(elements, data,
                      settings.ROLLGEN_REGISTRATIONS_PER_PAGE_POLLING_BOOK)
            draw_footer(elements, gender_string, styles)

    if skipped_voters:
        data = [[STRINGS['voted'], STRINGS['the_names'], STRINGS['number']]]

        for voter in skipped_voters:
            data.append(
                ['', reshape(format_name(voter)), voter.registrant_number])
        log_voters("re-adding", skipped_voters)
        draw_header(elements, header_string, center_info, styles, station,
                    "book")
        draw_body(elements, data,
                  settings.ROLLGEN_REGISTRATIONS_PER_PAGE_POLLING_BOOK)
        draw_footer(elements, gender_string, styles)

    with out_of_disk_space_handler_context():
        doc.build(elements,
                  canvasmaker=NumberedCanvas,
                  onLaterPages=drawHnecLogo)

    return doc.n_pages
示例#12
0
def draw_footer(elements, gender_string, styles):
    elements.append(Paragraph(gender_string, styles['PageBottom']))
    elements.append(PageBreak())
示例#13
0
    def _create_licence_purpose(elements, selected_activity, issued_purpose):
        '''
        Creates the licence purpose details per page available on the activity.
        '''

        # delegation holds the dates, licencee and issuer details.
        delegation = []
        sequence = purpose.purpose_sequence
        licence_display = '{0}-{1}-{2}'.format(licence.licence_number,
                                               sequence,
                                               issued_purpose.purpose.code)
        licence_purpose = issued_purpose.purpose.name
        elements.append(
            Paragraph(licence_purpose.upper(),
                      styles['InfoTitleVeryLargeCenter']))
        elements.append(
            Paragraph(
                'Regulation {}, Biodiversity Conservation Regulations 2018'.
                format(issued_purpose.purpose.regulation), styles['Center']))

        # applicant details
        delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        if application.applicant_type \
                == application.APPLICANT_TYPE_ORGANISATION:
            address = application.org_applicant.address
            pass
        elif application.applicant_type == application.APPLICANT_TYPE_PROXY:
            address = application.proxy_applicant.residential_address
            pass
        else:
            # applic.applicant_type == application.APPLICANT_TYPE_SUBMITTER
            address = application.submitter.residential_address

        address_paragraphs = [
            Paragraph(address.line1, styles['Left']),
            Paragraph(address.line2, styles['Left']),
            Paragraph(address.line3, styles['Left']),
            Paragraph(
                '%s %s %s' %
                (address.locality, address.state, address.postcode),
                styles['Left']),
            Paragraph(address.country.name, styles['Left'])
        ]

        delegation.append(
            Table([[[
                Paragraph('Licence Number', styles['BoldLeft']),
                Paragraph('Licence Holder', styles['BoldLeft']),
                Paragraph('Address', styles['BoldLeft'])
            ], [Paragraph(licence_display, styles['Left'])] + [
                Paragraph(licence.current_application.applicant,
                          styles['Left'])
            ] + address_paragraphs]],
                  colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
                  style=licence_table_style))

        # dates
        dates_licensing_officer_table_style = TableStyle([
            ('VALIGN', (0, 0), (-2, -1), 'TOP'),
            ('VALIGN', (0, 0), (-1, -1), 'BOTTOM')
        ])

        delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        date_headings = [
            Paragraph('Date of Issue', styles['BoldLeft']),
            Paragraph('Date Valid From', styles['BoldLeft']),
            Paragraph('Date of Expiry', styles['BoldLeft'])
        ]
        date_values = [
            Paragraph(issued_purpose.issue_date.strftime('%d/%m/%Y'),
                      styles['Left']),
            Paragraph(issued_purpose.start_date.strftime('%d/%m/%Y'),
                      styles['Left']),
            Paragraph(issued_purpose.expiry_date.strftime('%d/%m/%Y'),
                      styles['Left'])
        ]

        if issued_purpose.is_reissued:
            date_headings.insert(
                0, Paragraph('Original Date of Issue', styles['BoldLeft']))
            date_values.insert(
                0, Paragraph(issued_purpose.original_issue_date,
                             styles['Left']))

        delegation.append(
            Table([[date_headings, date_values]],
                  colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
                  style=dates_licensing_officer_table_style))

        delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        elements.append(KeepTogether(delegation))

        # species
        species_ids = issued_purpose.purpose.get_species_list
        if species_ids:
            elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
            elements.append(Paragraph('SPECIES', styles['BoldLeft']))
            elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
            species = LicenceSpecies.objects.values_list('data').filter(
                specie_id__in=species_ids)
            speciesList = ListFlowable([
                Paragraph(s[0][0]['vernacular_names'], styles['Left'])
                for s in species
            ],
                                       bulletFontName=BOLD_FONTNAME,
                                       bulletFontSize=MEDIUM_FONTSIZE)
            elements.append(speciesList)
            elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        try:
            # copy-to-licence sections with terms and additional information.
            activity_util = ActivitySchemaUtil(selected_activity.application)
            terms = selected_activity.additional_licence_info['terms']
            for term in terms:
                header = term['header']
                if not header:
                    continue
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
                elements.append(Paragraph(header.upper(), styles['BoldLeft']))
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
                text = activity_util.get_ctl_text(term)
                elements.append(Paragraph(text, styles['Left']))
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        except BaseException:
            pass

        # PurposeSpecies Section
#        for s in purpose.purpose_species_json:
#            if s.has_key('is_additional_info') and s['is_additional_info']:
#                continue
#
#            if s['details']:
#                parser = HtmlParser(s['details'])
#
#                # Get and Display Purpose Species Header
#                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
#                elements.append(
#                    Paragraph(
#                        s['header'],
#                        styles['BoldLeft']
#                    )
#                )
#                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
#
#                purposeSpeciesList = add_parsed_details(parser, list_flowable=False)
#                for info_item in purposeSpeciesList:
#                    elements.append(KeepTogether(info_item))

        for s in purpose.purpose_species_json:
            if 'is_additional_info' in s and s['is_additional_info']:
                continue

            if s['details']:
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
                purposeSpeciesList, listcounter = html_to_rl(
                    s['details'], styles)

                for info_item in purposeSpeciesList:
                    elements.append(KeepTogether(info_item))

        # End PurposeSpecies Section

        # application conditions
        activity_conditions = selected_activity.application.conditions.filter(
            licence_activity_id=selected_activity.licence_activity_id,
            licence_purpose_id=issued_purpose.purpose.id)

        if activity_conditions.exists():
            elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
            elements.append(Paragraph('CONDITIONS', styles['BoldLeft']))
            #elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

            # Conditions Section
            #            conditionList = []
            #            for s in activity_conditions.order_by('order'):
            #                parser = HtmlParser(s.condition)
            #                conditionList += add_parsed_details(parser, list_flowable=False)
            #                #elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

            #            conditionList = ListFlowable(
            #                conditionList,
            #                bulletFontName=BOLD_FONTNAME, bulletFontSize=MEDIUM_FONTSIZE
            #            )
            #            elements.append(conditionList)

            listcounter = 0
            conditionList = []
            for s in activity_conditions.order_by('order'):
                #_conditionList, listcounter += html_to_rl(s.condition, styles)
                _conditionList, listcounter = html_to_rl(
                    s.condition_text, styles, listcounter)
                conditionList += _conditionList

            for info_item in conditionList:
                elements.append(KeepTogether(info_item))

            # End Conditions Section

        elements += _layout_extracted_fields(licence.extracted_fields)
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        # signature block
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        issue_officer = '{} {}'.format(selected_activity.updated_by.first_name,
                                       selected_activity.updated_by.last_name)
        elements.append(Paragraph('____________________', styles['Left']))
        elements.append(Paragraph(issue_officer, styles['Left']))
        elements.append(Paragraph('LICENSING OFFICER', styles['Left']))
        elements.append(Paragraph('WILDLIFE PROTECTION BRANCH',
                                  styles['Left']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Delegate of CEO', styles['ItalicLeft']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        # additional information
        # 'is_additional_info' Section from Purposespecies
        #        for s in purpose.purpose_species_json:
        #            if s.has_key('is_additional_info') and s['is_additional_info'] and s['details']:
        #                parser = HtmlParser(s['details'])
        #
        #                # Get and Display Purpose Species Header
        #                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        #                elements.append(
        #                    Paragraph(
        #                        s['header'],
        #                        styles['BoldLeft']
        #                    )
        #                )
        #                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        #
        #                purposeSpeciesInfoList = add_parsed_details(parser, list_flowable=False)
        #                #elements.append(purposeSpeciesInfoList)
        #                for info_item in purposeSpeciesInfoList:
        #                    elements.append(KeepTogether(info_item))

        # additional information
        for s in purpose.purpose_species_json:
            if 'is_additional_info' in s and s['is_additional_info'] and s[
                    'details']:
                # Get and Display Purpose Species Header
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
                purposeSpeciesInfoList, listcounter = html_to_rl(
                    s['details'], styles)

                for info_item in purposeSpeciesInfoList:
                    elements.append(KeepTogether(info_item))
        # End PurposeSpecies Section

        if licence.has_additional_information_for(selected_activity):
            elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
            elements.append(
                Paragraph('ADDITIONAL INFORMATION', styles['BoldLeft']))
            #elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

            conditions = activity_conditions
            infos = []
            c_num = 0
            for c_id, condition in enumerate(conditions.order_by('order')):
                info = None
                if condition.standard_condition:
                    info = condition.standard_condition.additional_information
                    c_num = c_id + 1
                if info:
                    infos.append('{0} (related to condition no.{1})'.format(
                        info.encode('utf8'), c_num))

            # Conditions Section


#            for s in infos:
#                parser = HtmlParser(s)
#                infoList = add_parsed_details(parser)
#                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
#                elements.append(infoList)

            for s in infos:
                infoList, listcounter = html_to_rl(s, styles)
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

                #elements.append(infoList)
                for info_item in infoList:
                    elements.append(KeepTogether(info_item))

            # End Conditions Section

        elements.append(PageBreak())
示例#14
0
def summary_reportlab(shifts, images=None, output=None):
    """Print a pdf report of the beam shift results

    'shifts' input is a dictionary in form { "GA0E240":[xshift, yshift] }
    where x and y are in the image (hence BEV) coordinate system
    """

    # Check if single image or list is provided
    images_to_plot = []
    if images is None:
        images_to_plot = []
    elif type(images) is list:
        images_to_plot = images
    elif type(images) is str:
        images_to_plot.append(images)
    else:
        print(
            "Provide a link to image file or list of links for summary report")

    if output is None:
        output = "xrv124 summary.pdf"

    # Convert x,y shifts to total displacement
    displacements = get_total_displacement(shifts)

    # Data formatted for PDF table
    table_data = get_table_data(displacements)

    # Set up document
    doc = SimpleDocTemplate(output,
                            pagesize=letter,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=72,
                            bottomMargin=18)

    # Story is a list of "Flowables" that will be converted into the PDF
    Story = []

    # Make some paragraph styles we can call later
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
    styles.add(
        ParagraphStyle(name='Indent', alignment=TA_JUSTIFY, leftIndent=20))
    styles.add(
        ParagraphStyle(name='Underline',
                       alignment=TA_JUSTIFY,
                       underlineWidth=1))

    title = '<font size="15"><u> Logos XRV-124 monthly QA results </u></font>'
    Story.append(Paragraph(title, styles["Justify"]))
    Story.append(Spacer(1, 50))

    ############# TABLE OF RESULTS
    Story.append(
        Paragraph("Summary of beam shift results:", styles["Underline"]))
    Story.append(Spacer(1, 20))

    #### Insert a FAIL manually
    ###table_data[5][2] = "FAIL"

    # Get table coordinates of FAIL cells
    fails = []
    for i, row in enumerate(table_data):
        for j, el in enumerate(row):
            if table_data[i][j] == "FAIL":
                ###print(j,i)
                fails.append((j, i))

    t = Table(table_data)
    t.setStyle(
        TableStyle([
            ('BACKGROUND', (0, 0), (0, len(table_data)), colors.lightblue),
            ('BACKGROUND', (0, 0), (len(table_data[0]), 0), colors.lightblue)
        ]))
    # Make fails red
    for coord in fails:
        t.setStyle(
            TableStyle([('BACKGROUND', coord, coord, colors.lightcoral)]))

    Story.append(t)

    ########## LIST all beams with displacements > 1, 1.5 and 2mm
    beams_gt_1mm = {}
    beams_gt_1pt5mm = {}
    beams_gt_2mm = {}

    for key in displacements:
        ga = str(key.split("GA")[1].split("E")[0])
        en = key.split("E")[1] + " MeV"
        if displacements[key] > 2.0:
            # Add new element of to existing list
            if ga in beams_gt_2mm:
                beams_gt_2mm[ga] = beams_gt_2mm[ga] + [en]
            else:
                beams_gt_2mm[ga] = [en]
        elif displacements[key] > 1.5:
            if ga in beams_gt_1pt5mm:
                beams_gt_1pt5mm[ga] = beams_gt_1pt5mm[ga] + [en]
            else:
                beams_gt_1pt5mm[ga] = [en]
        if displacements[key] > 1:
            if ga in beams_gt_1mm:
                beams_gt_1mm[ga] = beams_gt_1mm[ga] + [en]
            else:
                beams_gt_1mm[ga] = [en]

    if len(beams_gt_1mm) > 0:
        Story.append(Spacer(1, 40))
        Story.append(
            Paragraph("List of beams with displacements > 1 mm:",
                      styles["Justify"]))
        for ga in beams_gt_1mm:
            p = "GA {}: {}".format(ga, beams_gt_1mm[ga])
            Story.append(Paragraph(p, styles["Indent"]))
    if len(beams_gt_1pt5mm) > 0:
        Story.append(Spacer(1, 40))
        Story.append(
            Paragraph("List of beams with displacements > 1.5 mm:",
                      styles["Justify"]))
        for ga in beams_gt_1pt5mm:
            p = "GA {}: {}".format(ga, beams_gt_1pt5mm[ga])
            Story.append(Paragraph(p, styles["Indent"]))
    if len(beams_gt_2mm) > 0:
        Story.append(Spacer(1, 40))
        Story.append(
            Paragraph("List of beams with displacements > 2 mm:",
                      styles["Justify"]))
        for ga in beams_gt_2mm:
            p = "GA {}: {}".format(ga, beams_gt_2mm[ga])
            Story.append(Paragraph(p, styles["Indent"]))
    Story.append(Spacer(1, 20))

    ############ IMAGES we want to include
    for img in images_to_plot:
        Story.append(PageBreak())
        #Story.append(Paragraph( "Spot shifts grouped by gantry angle:", styles["Justify"]))
        Story.append(Spacer(1, 20))
        im = Image(img, 7 * inch, 5.5 * inch)
        Story.append(im)

    ########## COMBINE ALL ELEMENTS OF Story into document
    doc.build(Story)
示例#15
0
def genPrintLabelPDFs(labelDataInput, defaultFileName=None):
    """labelDataInput = list of dictionaries formatted as: {DWC Column:'field value'}
       defaultFileName = the filename to use as the default when saving the pdf file."""

    labelData = labelDataInput
    xPaperSize = 5.50 * inch  #These values should be user preferences! (But it'll be a PITA to do)
    yPaperSize = 3.50 * inch
    #    yPaperSize = 5.50 * inch
    #    xPaperSize = 3.50 * inch
    customPageSize = (
        xPaperSize, yPaperSize
    )  #set up Paper size for labels, this should be user selectable in time.

    relFont = 12  #a font size which everything else relates to. Base normal text font size.

    xMarginProportion = 0
    yMarginProportion = 0  #Padding on tables are functionally the margins in our use. (We're claiming most of paper)
    xMargin = xMarginProportion * xPaperSize  #Margin set up (dynamically depending on paper sizes. Hopefully logical stuff).
    yMargin = xMarginProportion * yPaperSize

    #Style sheets below (many lines.. for various styles)
    def stylesheet(key):
        styles = {
            'default':
            ParagraphStyle(
                'default',
                fontName='Times-Roman',
                fontSize=relFont,
                leading=(relFont * 1.1),
                leftIndent=0,
                rightIndent=0,
                firstLineIndent=0,
                alignment=TA_LEFT,
                spaceBefore=0,
                spaceAfter=0,
                bulletFontName='Times-Roman',
                bulletFontSize=10,
                bulletIndent=0,
                backColor=None,
                wordWrap=(xPaperSize, yPaperSize),
                borderWidth=0,
                borderPadding=0,
                borderColor=None,
                borderRadius=None,
                allowWidows=1,
                allowOrphans=0,
                textTransform=None,  # options: 'uppercase' | 'lowercase' | None
                endDots=None,
                splitLongWords=1,
            ),
        }
        styles['title'] = ParagraphStyle(
            'title',
            parent=styles['default'],
            fontName='Times-Bold',
            fontSize=relFont * 1.2,
            alignment=TA_CENTER,
        )
        styles['collectionNameSTY'] = ParagraphStyle(
            'collectionNameSTY',
            parent=styles['title'],
            fontName='Times',
            fontSize=relFont * 1.2,
            alignment=TA_CENTER,
        )
        styles['samplingEffortSTY'] = ParagraphStyle(
            'samplingEffortSTY',
            parent=styles['title'],
            fontName='Times-Bold',
            fontSize=relFont * 1.18,
            alignment=TA_CENTER,
        )
        styles['dateSTY'] = ParagraphStyle(
            'dateSTY',
            parent=styles['title'],
            fontName='Times',
            fontSize=relFont * 1.18,
            alignment=TA_RIGHT,
        )
        styles['authoritySTY'] = ParagraphStyle('authoritySTY',
                                                parent=styles['default'],
                                                fontSize=relFont * 1.18,
                                                alignment=TA_LEFT)
        styles['sciNameSTY'] = ParagraphStyle('sciNameSTY',
                                              parent=styles['default'],
                                              fontSize=relFont * 1.18,
                                              alignment=TA_LEFT,
                                              spaceAfter=1)
        styles['sciNameSTYSmall'] = ParagraphStyle('sciNameSTYSmall',
                                                   parent=styles['default'],
                                                   fontSize=relFont,
                                                   alignment=TA_LEFT,
                                                   spaceAfter=1)
        styles['defaultSTYSmall'] = ParagraphStyle(
            'defaultSTYSmall',
            parent=styles['default'],
            fontSize=relFont * .80,
        )

        styles['verifiedBySTY'] = ParagraphStyle(
            'verifiedBySTY',
            parent=styles['default'],
            fontSize=relFont * .80,
            alignment=TA_CENTER,
            borderPadding=2,
        )
        styles['rightSTY'] = ParagraphStyle(
            'rightSTY',
            parent=styles['default'],
            alignment=TA_RIGHT,
            spaceAfter=1,
        )
        styles['prefixLeftSTY'] = ParagraphStyle('prefixLeftSTY',
                                                 parent=styles['default'],
                                                 alignment=TA_LEFT,
                                                 spaceAfter=1,
                                                 fontName='Times-Bold')
        styles['prefixRightSTY'] = ParagraphStyle('prefixRightSTY',
                                                  parent=styles['default'],
                                                  alignment=TA_RIGHT,
                                                  spaceAfter=1,
                                                  fontName='Times-Bold')
        styles['countySTY'] = ParagraphStyle('countySTY',
                                             parent=styles['default'],
                                             alignment=TA_CENTER,
                                             spaceAfter=1,
                                             fontName='Times')
        return styles.get(key)

    tableSty = [  #Default table style
        ('LEFTPADDING', (0, 0), (-1, -1), 0),
        ('RIGHTPADDING', (0, 0), (-1, -1), 0),
        ('TOPPADDING', (0, 0), (-1, -1), 0),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 0)
    ]

    #helper functions to keep the 'flowables' code more legible.

    def Para(textField1, styleKey, prefix='', suffix=''):
        if len(dfl(textField1)
               ) > 0:  #If the field has a value insert it, otherwise blank row
            return Paragraph(
                ('<b>{}</b>'.format(prefix)) + dfl(textField1) + suffix,
                style=stylesheet(styleKey))
        else:
            return Paragraph('', style=stylesheet(styleKey))

    def verifiedByPara(textField1, styleKey):
        if len(dfl(textField1)
               ) > 0:  #If the field has a value insert it, otherwise blank row
            return Paragraph('<i>Verified by {}</i>'.format(dfl(textField1)),
                             style=stylesheet(styleKey))
        else:
            return Paragraph('', style=stylesheet(styleKey))

    def sciName(textfield1, textfield2, styleKey, prefix=''):
        if len(dfl(textfield1)) > 0:
            return Paragraph(
                ('<i>{}</i>'.format(dfl(textfield1))) + ' ' + dfl(textfield2),
                style=stylesheet(styleKey))
        else:
            return Paragraph('', style=stylesheet(styleKey))

    def collectedByPara(textfield1, textfield2, styleKey, prefix=''):
        if len(dfl(textfield1)) > 0:
            if len(dfl(textfield2)) > 0:
                return Paragraph(('<b>{}</b>'.format(prefix)) +
                                 dfl(textfield1) + ' with ' + dfl(textfield2),
                                 style=stylesheet(styleKey))
            else:
                return Paragraph(
                    ('<b>{}</b>'.format(prefix)) + dfl(textfield1),
                    style=stylesheet(styleKey))
        else:
            return Paragraph('', style=stylesheet(styleKey))

    def cultivationStatusChecker(textfield1, styleKey):
        if str(dfl(textfield1)) == 'cultivated':
            return Paragraph('<b>Cultivated specimen</b>',
                             style=stylesheet(styleKey))
        else:
            return Paragraph('', style=stylesheet('default'))

    def gpsCoordStringer(textfield1, textfield2, textfield3, textfield4,
                         styleKey):
        gpsString = []
        if len(dfl(textfield1)) > 0:
            if (dfl(textfield1) and dfl(textfield2)):
                # min([len(dfl(textfield1)),len(dfl(textfield2))]) testing length control.
                gpsString.append('<b>GPS: </b>' + dfl(textfield1) + ', ' +
                                 dfl(textfield2))
            if dfl(textfield3):
                gpsString.append(' ± ' + dfl(textfield3) + 'm')
            if dfl(textfield4):
                gpsString.append(', <b>Elevation: </b>' + dfl(textfield4) +
                                 'm')

            return Paragraph(''.join(gpsString), style=stylesheet(styleKey))

    #############Logo Work#################################
    ##############################################################################
    #
    #logoPath = 'ucht.jpg'   # This should be determined by the user dialog open option.
    #
    #def getLogo(logoPath):
    #    if logoPath:
    #        return Image(logoPath, width = 40, height =30.6) #These values should be handled dynamically!
    ######Barcode work(Catalog Number)######

    def newHumanText(self):
        return self.stop and self.encoded[1:-1] or self.encoded

    def createBarCodes(
    ):  #Unsure of the benefits downsides of using extended vs standard?
        if len(dfl('catalogNumber')) > 0:
            barcodeValue = dfl('catalogNumber')
            code39._Code39Base._humanText = newHumanText  #Note, overriding the human text from this library to omit the stopcode ('+')
            barcode39Std = code39.Standard39(
                barcodeValue,
                barHeight=(yPaperSize * .10),
                barWidth=((xPaperSize * 0.28) / (len(barcodeValue) * 13 + 35)),
                humanReadable=True,
                quiet=False,
                checksum=0)
            #^^^Note width is dynamic, but I don't know the significe of *13+35 beyond making it work.
            return barcode39Std
        else:
            return ''

    elements = []  # a list to dump the flowables into for pdf generation
    for labelFieldsDict in labelData:

        def dfl(key):  # dict lookup helper function
            value = labelFieldsDict.get(
                key, '')  # return empty string if no result from lookup.
            return str(value)

    #Building list of flowable elements below

        if len(
                dfl('catalogNumber')
        ) > 0:  #If the catalog number is known, add the barcode. If not, don't.
            row0 = Table([[
                Para('collectionName', 'collectionNameSTY'),
                createBarCodes()
            ]],
                         colWidths=(xPaperSize * .67, xPaperSize * .29),
                         rowHeights=None,
                         style=[
                             ('VALIGN', (0, 0), (0, -1), 'TOP'),
                             ('ALIGN', (0, 0), (0, 0), 'LEFT'),
                             ('ALIGN', (1, 0), (1, 0), 'RIGHT'),
                         ])
        else:
            row0 = Para('collectionName', 'collectionNameSTY')

        row1 = Table([[Para('samplingEffort', 'samplingEffortSTY')],
                      [verifiedByPara('verifiedBy', 'verifiedBySTY')]],
                     colWidths=xPaperSize * .98,
                     rowHeights=None,
                     style=[('BOTTOMPADDING', (0, 0), (-1, -1), 2)])
        #bookmark
        #ScientificName Row Dynamic Formatting

        scientificNameElement = sciName('scientificName',
                                        'scientificNameAuthorship',
                                        'sciNameSTY')
        try:  #Test if Scienftific Name can Share a row with Event Date.
            scientificNameElement.wrap(
                1400, 1400
            )  #Test wrap the string in a large environment to get it's desired ideal width.
            sciNameParaWidth = scientificNameElement.getActualLineWidths0()[0]
            sciHeight = scientificNameElement.height

        except (AttributeError, IndexError) as e:
            sciNameParaWidth = 0

        if sciNameParaWidth > xPaperSize * .96:  #If the string is so large as to not fit, even alone then shrink font and split lines into two rows.
            row2 = Table(
                [
                    [Para('eventDate', 'dateSTY')],
                    [Spacer(width=xPaperSize * .98, height=sciHeight)
                     ],  #Add spacer between rows for formatting.
                    [
                        sciName('scientificName', 'scientificNameAuthorship',
                                'sciNameSTYSmall')
                    ]
                ],
                colWidths=xPaperSize * .98,
                rowHeights=None,
                style=tableSty)

        elif sciNameParaWidth > xPaperSize * .80:  #If the string is too big to share row with event date, split lines into rows.
            row2 = Table(
                [
                    [Para('eventDate', 'dateSTY')],
                    [Spacer(width=xPaperSize * .98, height=sciHeight)
                     ],  #Add spacer between rows for formatting.
                    [
                        sciName('scientificName', 'scientificNameAuthorship',
                                'sciNameSTY')
                    ]
                ],
                colWidths=xPaperSize * .98,
                rowHeights=None,
                style=tableSty)
        else:
            row2 = Table([[
                sciName('scientificName', 'scientificNameAuthorship',
                        'sciNameSTY'),
                Para('eventDate', 'dateSTY')
            ]],
                         colWidths=(xPaperSize * .80, xPaperSize * .18),
                         rowHeights=None,
                         style=tableSty)

        row3 = Table([[Para('locality', 'default')]],
                     rowHeights=None,
                     style=tableSty)

        #Associated Taxa Dynamic Formatting
        if dfl('associatedTaxa'
               ) == '':  #If associated taxa is not used, give up the y space.
            associatedTaxaHeight = 0
            associatedTaxaStyle = 'defaultSTYSmall'  #This entire block is not functioning the way it was planned to.
        else:
            associatedTaxaHeight = .15 * yPaperSize  #Otherwise, devote some space, then test it's useage.
            associatedTaxaElement = Para(
                'associatedTaxa', 'default',
                'Associated taxa: ')  #Test build for height
            try:
                associatedTaxaParaHeight = associatedTaxaElement.wrap(
                    xPaperSize * .98, 1
                )[1]  #Test wrap the string in a large environment to get necessary height.
            except (AttributeError, IndexError) as e:
                print('error ', e)
                associatedTaxaParaHeight = 0

            if associatedTaxaParaHeight > associatedTaxaHeight:  #If the string is too large, reduce the font size.
                associatedTaxaStyle = 'defaultSTYSmall'
            else:
                associatedTaxaStyle = 'default'  #otherwise, use the normal height
        row4 = Table([[
            Para('associatedTaxa', associatedTaxaStyle, 'Associated taxa: ')
        ]],
                     rowHeights=None,
                     style=tableSty)
        #Note, associatedTaxa only reduces size if it is too large. At some extream point we'll need to consider trunication.

        if dfl('individualCount') != '':
            row5 = Table([[
                Para('habitat', 'default', 'Habitat: '),
                Para('individualCount', 'rightSTY', 'Approx. ≥ ', ' on site.')
            ]],
                         colWidths=(xPaperSize * .68, xPaperSize * .30),
                         rowHeights=None,
                         style=[('VALIGN', (1, 0), (1, 0), 'CENTER'),
                                ('ALIGN', (0, 0), (0, 0), 'LEFT'),
                                ('ALIGN', (1, 0), (1, 0), 'RIGHT'),
                                ('LEFTPADDING', (0, 0), (-1, -1), 0),
                                ('RIGHTPADDING', (0, 0), (-1, -1), 0),
                                ('TOPPADDING', (0, 0), (-1, -1), 0),
                                ('BOTTOMPADDING', (0, 0), (-1, -1), 0)])
        else:
            row5 = Table([[Para('habitat', 'default', 'Habitat: ')]],
                         style=tableSty)

        if dfl(
                'establishmentMeans'
        ) == 'cultivated':  #If establishmentMeans status is not 'cultivated' (based on cultivated status in mobile app) then forfit the space in case Substrate field is long.
            row6 = Table([[
                Para('substrate', 'default', 'Substrate: '),
                cultivationStatusChecker('establishmentMeans', 'rightSTY')
            ]],
                         colWidths=(xPaperSize * .68, xPaperSize * .30),
                         rowHeights=None,
                         style=tableSty)

        else:
            row6 = Table([[Para('substrate', 'default', 'Substrate: ')]],
                         style=tableSty)

        row7 = [
            collectedByPara('recordedBy', 'associatedCollectors', 'default',
                            'Collected by: ')
        ]

        row6_5 = Table(
            [[Para('locationRemarks', 'default', 'Location Remarks: ')]],
            style=tableSty)
        #Note locationRemarks is in testing, may not stay!

        row6_7 = Table(
            [[Para('occurrenceRemarks', 'default', 'Occurence Remarks: ')]],
            style=tableSty)

        if dfl('identifiedBy') != '':
            row7_5 = Table(
                [[Para('identifiedBy', 'default', 'Determined by: ')]],
                style=tableSty)
        # TODO: Add all tableList (row) objects to a loop which checks for content and appends else returns None
        # ...  Then Clean tableList for None objects

        tableList = [[row0], [row1], [row2], [row3], [row4], [row5], [row6],
                     [row6_5], [row6_7], [row7]]

        #Testing if GPS String can fit on one row with the field number. If not, split them into two rows.
        gpsStrElement = gpsCoordStringer('decimalLatitude', 'decimalLongitude',
                                         'coordinateUncertaintyInMeters',
                                         'minimumElevationInMeters',
                                         'rightSTY')
        try:
            gpsStrElement.wrap(xPaperSize * .98, yPaperSize * .98)
            gpsParaWidth = gpsStrElement.getActualLineWidths0()[0]
        except AttributeError:
            gpsParaWidth = 0

        if gpsParaWidth > xPaperSize * .65:
            row8 = Table(
                [[Para('otherCatalogNumbers', 'default', 'Field Number: ')]],
                style=tableSty)
            row9 = Table([[gpsStrElement]], style=tableSty)
            tableList.append([row8])

            if dfl('identifiedBy') != '':
                tableList.append([row7_5])

            tableList.append([row9])

        else:
            row8 = Table([[
                Para('otherCatalogNumbers', 'default', 'Field Number: '),
                gpsStrElement
            ]],
                         colWidths=(xPaperSize * .33, xPaperSize * .65),
                         rowHeights=None,
                         style=tableSty)
            tableList.append([row8])

            if dfl('identifiedBy') != '':
                tableList.append([row7_5])

        # append the determined by field

        docTableStyle = [  #Cell alignment and padding settings (not text align within cells)
            ('VALIGN', (0, 3), (0, -1), 'BOTTOM'),  #Rows 4-end align to bottom
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),  #All rows align to center
            ('LEFTPADDING', (0, 0), (-1, -1),
             0),  #ALL Rows padding on left to none
            ('RIGHTPADDING', (0, 0), (-1, -1),
             0),  #ALL Rows padding on right to none
            ('TOPPADDING', (0, 0), (-1, -1),
             3),  #ALL Rows padding on top to none
            ('BOTTOMPADDING', (0, 0), (-1, -1),
             0),  #ALL Rows padding on Bottom to none
            ('BOTTOMPADDING', (0, 0), (0, 0),
             3),  #ALL Rows padding on Bottom to none
            ('TOPPADDING', (0, 1), (0, 1), 6),  #Row 2 top padding to 6
            ('TOPPADDING', (0, 2), (0, 2), 6),  #Row 3 top padding to 6
            ('BOTTOMPADDING', (0, 2), (0, 2), 6),  #Row 3 bottom padding to 6
            #('NOSPLIT', (0,0),(-1,-1)),          #Makes Error if it won't fit. We should raise this error to user!
        ]

        docTable = Table(
            tableList,
            style=docTableStyle)  #build the table to test it's height

        wid, hei = docTable.wrap(
            0, 0)  #Determines how much space is used by the table
        spaceRemaining = (yPaperSize - hei - 10
                          )  #Determine how much is left on the page
        spaceFiller = [
            Spacer(width=0, height=(spaceRemaining / 3))
        ]  #assign half the remaining space to a filler (to distrib into two places.
        tableList.insert(
            4, spaceFiller
        )  #build from bottom up because it is less confusing for the index values.
        tableList.insert(3, spaceFiller)
        tableList.insert(2, spaceFiller)

        docTable = Table(tableList,
                         style=docTableStyle)  #build the final table

        #Add the flowables to the elements list.
        elements.append(docTable)
        elements.append(PageBreak())
#Bookmark
#Build the base document's parameters.
    labelFileName = filedialog.asksaveasfilename(initialdir=os.getcwd(),
                                                 defaultextension='.pdf',
                                                 initialfile=defaultFileName,
                                                 filetypes=(('pdf',
                                                             '*.pdf'), ),
                                                 title='Save Labels As')
    doc = BaseDocTemplate(labelFileName,
                          pagesize=customPageSize,
                          pageTemplates=[],
                          showBoundary=0,
                          leftMargin=xMargin,
                          rightMargin=xMargin,
                          topMargin=yMargin,
                          bottomMargin=yMargin,
                          allowSplitting=1,
                          title=None,
                          author=None,
                          _pageBreakQuick=1,
                          encrypt=None)

    #Function to build the pdf

    def build_pdf(flowables):
        doc.addPageTemplates([
            PageTemplate(frames=[
                platypusFrame(doc.leftMargin,
                              doc.bottomMargin,
                              doc.width,
                              doc.height,
                              topPadding=0,
                              bottomPadding=0,
                              id=None),
            ]),
        ])
        doc.build(flowables)

    #Actually build the pdf
    build_pdf(elements)

    #Open the file after it is built (maybe change/remove this later? Idealy, a preview or something

    def open_file(filename):
        if sys.platform == "win32":
            os.startfile(filename)
        else:
            opener = "open" if sys.platform == "darwin" else "xdg-open"
            subprocess.call([opener, filename])

    open_file(labelFileName)
示例#16
0
 def match_pages(self, match_report_and_report_content: list):
     pages = []
     for (match_report, match_content) in match_report_and_report_content:
         pages.extend(self.match_page(match_report, match_content))
         pages.append(PageBreak())
     return pages
示例#17
0
def pdf_head(canvas, news):
    index = -1
    while index < len(news):
        canvas.setFont("Helvetica-Bold", 11.5)
        canvas.drawString(1 * inch, 1 * inch, "Tech News Cluster")
        canvas.rect(1 * inch, 1.2 * inch, 6.5 * inch, 0.12 * inch, fill=1)
        for i in range(5):
            index += 1
            if index < len(news):
                #text_width = 8 if len(news[index]['headline']) > 65 else 11.5
                text_width = 8.5
                canvas.setFont("Helvetica-Bold", text_width)
                canvas.drawString(3 * inch, (1.7 + i * 2) * inch,
                                  news[index]['headline'])
                r1 = (3 * inch,
                      9 * inch - ((1.7 + i * 2) * inch - 1.55 * inch),
                      4 * inch, 9 * inch - ((1.7 + i * 2) * inch - 1.35 * inch)
                      )  # this is x1,y1,x2,y2
                canvas.linkURL(news[index]['link'], r1)
                canvas.drawString(3 * inch, (1.7 + i * 2) * inch + 1.3 * inch,
                                  'Read More.')

                if len(news[index]
                       ) > 3 and news[index]['related_link1'] is not None:
                    r1 = (5 * inch, 9 * inch -
                          ((1.7 + i * 2) * inch - 1.55 * inch), 6 * inch,
                          9 * inch - ((1.7 + i * 2) * inch - 1.35 * inch)
                          )  # this is x1,y1,x2,y2
                    canvas.linkURL(news[index]['related_link1'], r1)
                    canvas.drawString(5 * inch,
                                      (1.7 + i * 2) * inch + 1.3 * inch,
                                      'Related News 1.')

                if len(news[index]
                       ) > 4 and news[index]['related_link2'] is not None:
                    r1 = (6 * inch, 9 * inch -
                          ((1.7 + i * 2) * inch - 1.55 * inch), 7 * inch,
                          9 * inch - ((1.7 + i * 2) * inch - 1.35 * inch)
                          )  # this is x1,y1,x2,y2
                    canvas.linkURL(news[index]['related_link2'], r1)
                    canvas.drawString(6 * inch,
                                      (1.7 + i * 2) * inch + 1.3 * inch,
                                      'Related News 2.')

                if news[index]['image'] is not None:
                    canvas.drawImage('./picture_rotation/' +
                                     news[index]['image'].split('/')[-1],
                                     1 * inch, (1.7 + i * 2) * inch,
                                     width=1.8 * inch,
                                     height=1.2 * inch,
                                     preserveAspectRatio=True,
                                     anchor='c')
                else:
                    canvas.drawImage('./picture_rotation/news.jpg',
                                     1 * inch, (1.7 + i * 2) * inch,
                                     width=1.8 * inch,
                                     height=1.2 * inch,
                                     preserveAspectRatio=True,
                                     anchor='c')

                if i == 4:
                    P = PageBreak()
                    canvas.showPage()
                    break
示例#18
0
def _create_approval(approval_buffer, approval, proposal, copied_to_permit,
                     user):
    site_url = settings.SITE_URL
    every_page_frame = Frame(PAGE_MARGIN,
                             PAGE_MARGIN,
                             PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 160,
                             id='EveryPagesFrame')
    every_page_template = PageTemplate(id='EveryPages',
                                       frames=[every_page_frame],
                                       onPage=_create_approval_header)

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

    # this is the only way to get data into the onPage callback function
    doc.approval = approval
    doc.site_url = site_url
    region = approval.region if hasattr(approval, 'region') else ''
    district = approval.district if hasattr(approval, 'district') else ''
    region_district = '{} - {}'.format(region,
                                       district) if district else region

    approval_table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')])

    elements = []

    title = approval.title.encode('UTF-8')

    #Organization details

    address = proposal.applicant.organisation.postal_address
    #email = proposal.applicant.organisation.organisation_set.all().first().contacts.all().first().email
    #elements.append(Paragraph(email,styles['BoldLeft']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(
        Paragraph(_format_name(approval.applicant), styles['BoldLeft']))
    elements.append(Paragraph(address.line1, styles['BoldLeft']))
    elements.append(Paragraph(address.line2, styles['BoldLeft']))
    elements.append(Paragraph(address.line3, styles['BoldLeft']))
    elements.append(
        Paragraph(
            '%s %s %s' % (address.locality, address.state, address.postcode),
            styles['BoldLeft']))
    elements.append(Paragraph(address.country.name, styles['BoldLeft']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(
        Paragraph(approval.issue_date.strftime(DATE_FORMAT),
                  styles['BoldLeft']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    #elements.append(Paragraph(title, styles['InfoTitleVeryLargeCenter']))
    #elements.append(Paragraph(approval.activity, styles['InfoTitleLargeLeft']))
    elements.append(
        Paragraph(
            'APPROVAL OF PROPOSAL {} {} TO UNDERTAKE DISTURBANCE ACTIVITY IN {}'
            .format(title, proposal.lodgement_number,
                    region_district), styles['InfoTitleLargeLeft']))
    #import ipdb; ipdb.set_trace()
    #elements.append(Paragraph(approval.tenure if hasattr(approval, 'tenure') else '', styles['InfoTitleLargeRight']))

    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(
        Paragraph(
            'The submitted proposal {} {} has been assessed and approved. The approval is granted on the understanding that: '
            .format(title, proposal.lodgement_number), styles['BoldLeft']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    list_of_bullets = []
    list_of_bullets.append(
        'The potential impacts of the proposal on values the department manages have been removed or minimised to a level \'As Low As Reasonably Practicable\' (ALARP) and the proposal is consistent with departmental objectives, associated management plans and the land use category/s in the activity area.'
    )
    list_of_bullets.append(
        'Approval is granted for the period {} to {}.  This approval is not valid if {} makes changes to what has been proposed or the proposal has expired.  To change the proposal or seek an extension, the proponent must re-submit the proposal for assessment.'
        .format(approval.start_date.strftime(DATE_FORMAT),
                approval.expiry_date.strftime(DATE_FORMAT),
                _format_name(approval.applicant)))
    list_of_bullets.append(
        'The proponent accepts responsibility for advising {} of new information or unforeseen threats that may affect the risk of the proposed activity.'
        .format(settings.DEP_NAME_SHORT))
    list_of_bullets.append(
        'Information provided by {0} for the purposes of this proposal will not be provided to third parties without permission from {0}.'
        .format(settings.DEP_NAME_SHORT))
    list_of_bullets.append(
        'The proponent accepts responsibility for supervising and monitoring implementation of activity/ies to ensure compliance with this proposal. {} reserves the right to request documents and records demonstrating compliance for departmental monitoring and auditing.'
        .format(settings.DEP_NAME_SHORT))
    list_of_bullets.append(
        'Non-compliance with the conditions of the proposal may trigger a suspension or withdrawal of the approval for this activity.'
    )
    list_of_bullets.append(
        'Management actions listed in Appendix 1 are implemented.')

    understandingList = ListFlowable([
        ListItem(
            Paragraph(a, styles['Left']), bulletColour='black', value='circle')
        for a in list_of_bullets
    ],
                                     bulletFontName=BOLD_FONTNAME,
                                     bulletFontSize=SMALL_FONTSIZE,
                                     bulletType='bullet')
    #bulletFontName=BOLD_FONTNAME
    elements.append(understandingList)

    # proposal requirements
    requirements = proposal.requirements.all().exclude(is_deleted=True)
    if requirements.exists():
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(
            Paragraph(
                'The following requirements must be satisfied for the approval of the proposal not to be withdrawn:',
                styles['BoldLeft']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        conditionList = ListFlowable([
            Paragraph(a.requirement, styles['Left'])
            for a in requirements.order_by('order')
        ],
                                     bulletFontName=BOLD_FONTNAME,
                                     bulletFontSize=MEDIUM_FONTSIZE)
        elements.append(conditionList)

    # if copied_to_permit:
    #     elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    #     elements.append(Paragraph('Assessor Comments', styles['BoldLeft']))
    #     elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    #     for k,v in copied_to_permit:
    #         elements.append(Paragraph(v.encode('UTF-8'), styles['Left']))
    #         elements.append(Paragraph(k.encode('UTF-8'), styles['Left']))
    #         elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    elements += _layout_extracted_fields(approval.extracted_fields)

    # additional information
    '''if approval.additional_information:
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Additional Information', styles['BoldLeft']))
        elements += _layout_paragraphs(approval.additional_information)'''

    # delegation holds the dates, approvale and issuer details.
    delegation = []

    # dates and licensing officer
    # dates_licensing_officer_table_style = TableStyle([('VALIGN', (0, 0), (-2, -1), 'TOP'),
    #                                                   ('VALIGN', (0, 0), (-1, -1), 'BOTTOM')])

    # delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    # date_headings = [Paragraph('Date of Issue', styles['BoldLeft']), Paragraph('Valid From', styles['BoldLeft']),
    #                  Paragraph('Date of Expiry', styles['BoldLeft'])]
    # date_values = [Paragraph(approval.issue_date.strftime(DATE_FORMAT), styles['Left']),
    #                Paragraph(approval.start_date.strftime(DATE_FORMAT), styles['Left']),
    #                Paragraph(approval.expiry_date.strftime(DATE_FORMAT), styles['Left'])]

    # if approval.original_issue_date is not None:
    #     date_headings.insert(0, Paragraph('Original Date of Issue', styles['BoldLeft']))
    #     date_values.insert(0, Paragraph(approval.original_issue_date.strftime(DATE_FORMAT), styles['Left']))

    # delegation.append(Table([[date_headings, date_values]],
    #                         colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
    #                         style=dates_licensing_officer_table_style))

    # proponent details
    # delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    # address = proposal.applicant.organisation.postal_address
    # address_paragraphs = [Paragraph(address.line1, styles['Left']), Paragraph(address.line2, styles['Left']),
    #                       Paragraph(address.line3, styles['Left']),
    #                       Paragraph('%s %s %s' % (address.locality, address.state, address.postcode), styles['Left']),
    #                       Paragraph(address.country.name, styles['Left'])]
    # delegation.append(Table([[[Paragraph('Licensee:', styles['BoldLeft']), Paragraph('Address', styles['BoldLeft'])],
    #                           [Paragraph(_format_name(approval.applicant),
    #                                      styles['Left'])] + address_paragraphs]],
    #                         colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
    #                         style=approval_table_style))
    if user.phone_number:
        contact_number = user.phone_number
    elif user.mobile_number:
        contact_number = user.mobile_number
    else:
        contact_number = settings.DEP_PHONE

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(
        Paragraph(
            'Should you have any queries about this approval, please contact {} {}, '
            'on {} or by email at {}'.format(user.first_name, user.last_name,
                                             contact_number, user.email),
            styles['Left']))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(
        Paragraph(
            'To provide feedback on the system used to submit the approval or update contact details, please '
            'contact {} Works Coordinator - {}'.format(
                settings.SYSTEM_NAME_SHORT, settings.SUPPORT_EMAIL),
            styles['Left']))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('Approved on behalf of the', styles['Left']))
    delegation.append(
        Paragraph('{}'.format(settings.DEP_NAME), styles['BoldLeft']))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    delegation.append(
        Paragraph('{} {}'.format(user.first_name, user.last_name),
                  styles['Left']))
    delegation.append(Paragraph('{}'.format(region_district), styles['Left']))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(
        Paragraph(approval.issue_date.strftime(DATE_FORMAT), styles['Left']))

    elements.append(KeepTogether(delegation))

    # Appendix section
    elements.append(PageBreak())
    elements.append(
        Paragraph('Appendix 1 - Management Actions', styles['BoldLeft']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    if copied_to_permit:
        # for k,v in copied_to_permit:
        #     elements.append(Paragraph(v.encode('UTF-8'), styles['Left']))
        #     elements.append(Paragraph(k.encode('UTF-8'), styles['Left']))
        #     elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        for item in copied_to_permit:
            for key in item:
                elements.append(Paragraph(key.encode('UTF-8'), styles['Left']))
                elements.append(
                    Paragraph(item[key].encode('UTF-8'), styles['Left']))
    else:
        elements.append(
            Paragraph('There are no management actions.', styles['Left']))

    doc.build(elements)

    return approval_buffer
                    ptext = '<font size=14>Alternativ kannst du mithilfe der Nextcloud-App folgenden QR-Code scannen:</font>'
                else:
                    ptext = '<font size=14>Alternativ können Sie mithilfe der Nextcloud-App folgenden QR-Code scannen:</font>'
            else:
                ptext = '<font size=14>Alternatively, you can scan the following QR-Code in the Nextcloud app:</font>'
            Story.append(Paragraph(ptext, styles["Normal"]))
            Story.append(Spacer(1, 24))
            # adds qr-code to pdf-file
            im2 = Image(os.path.join(tmp_dir, row[0] + ".jpg"), 200, 200)
            Story.append(im2)
            del im2
            if config_pdfOneDoc == 'no':
                # create pdf-file (single documents)
                doc.build(Story)
            else:
                Story.append(PageBreak())
                # create pdf-file (one document)
if config_pdfOneDoc == 'yes':
    doc.build(Story)

# Clean up tmp-folder
filelist = [f for f in os.listdir(tmp_dir)]
for f in filelist:
    os.remove(os.path.join(tmp_dir, f))

if config_EduDocs == 'yes':
    print("")
    print(
        "###################################################################################"
    )
    print(
    def test0(self):
        """Test...

        The story should contain...

        Features to be visually confirmed by a human being are:

            1. ...
            2. ...
            3. ...
        """
        if rl_invariant: random.seed(1854640162)
        story = []
        SA = story.append

        #need a style
        styNormal = ParagraphStyle('normal')
        styGreen = ParagraphStyle('green', parent=styNormal, textColor=green)

        styDots = ParagraphStyle('styDots', parent=styNormal, endDots='.')
        styDots1 = ParagraphStyle('styDots1',
                                  parent=styNormal,
                                  endDots=ABag(text=' -',
                                               dy=2,
                                               textColor='red'))
        styDotsR = ParagraphStyle('styDotsR',
                                  parent=styNormal,
                                  alignment=TA_RIGHT,
                                  endDots=' +')
        styDotsC = ParagraphStyle('styDotsC',
                                  parent=styNormal,
                                  alignment=TA_CENTER,
                                  endDots=' *')
        styDotsJ = ParagraphStyle('styDotsJ',
                                  parent=styNormal,
                                  alignment=TA_JUSTIFY,
                                  endDots=' =')

        istyDots = ParagraphStyle('istyDots',
                                  parent=styNormal,
                                  firstLineIndent=12,
                                  leftIndent=6,
                                  endDots='.')
        istyDots1 = ParagraphStyle('istyDots1',
                                   parent=styNormal,
                                   firstLineIndent=12,
                                   leftIndent=6,
                                   endDots=ABag(text=' -',
                                                dy=2,
                                                textColor='red'))
        istyDotsR = ParagraphStyle('istyDotsR',
                                   parent=styNormal,
                                   firstLineIndent=12,
                                   leftIndent=6,
                                   alignment=TA_RIGHT,
                                   endDots=' +')
        istyDotsC = ParagraphStyle('istyDotsC',
                                   parent=styNormal,
                                   firstLineIndent=12,
                                   leftIndent=6,
                                   alignment=TA_CENTER,
                                   endDots=' *')
        istyDotsJ = ParagraphStyle('istyDotsJ',
                                   parent=styNormal,
                                   firstLineIndent=12,
                                   leftIndent=6,
                                   alignment=TA_JUSTIFY,
                                   endDots=' =')

        styNormalCJK = ParagraphStyle('normal', wordWrap='CJK')
        styDotsCJK = ParagraphStyle('styDots',
                                    parent=styNormalCJK,
                                    endDots='.')
        styDots1CJK = ParagraphStyle('styDots1',
                                     parent=styNormalCJK,
                                     endDots=ABag(text=' -',
                                                  dy=2,
                                                  textColor='red'))
        styDotsRCJK = ParagraphStyle('styDotsR',
                                     parent=styNormalCJK,
                                     alignment=TA_RIGHT,
                                     endDots=' +')
        styDotsCCJK = ParagraphStyle('styDotsC',
                                     parent=styNormalCJK,
                                     alignment=TA_CENTER,
                                     endDots=' *')
        styDotsJCJK = ParagraphStyle('styDotsJ',
                                     parent=styNormalCJK,
                                     alignment=TA_JUSTIFY,
                                     endDots=' =')

        istyDotsCJK = ParagraphStyle('istyDots',
                                     parent=styNormalCJK,
                                     firstLineIndent=12,
                                     leftIndent=6,
                                     endDots='.')
        istyDots1CJK = ParagraphStyle('istyDots1',
                                      parent=styNormalCJK,
                                      firstLineIndent=12,
                                      leftIndent=6,
                                      endDots=ABag(text=' -',
                                                   dy=2,
                                                   textColor='red'))
        istyDotsRCJK = ParagraphStyle('istyDotsR',
                                      parent=styNormalCJK,
                                      firstLineIndent=12,
                                      leftIndent=6,
                                      alignment=TA_RIGHT,
                                      endDots=' +')
        istyDotsCCJK = ParagraphStyle('istyDotsC',
                                      parent=styNormalCJK,
                                      firstLineIndent=12,
                                      leftIndent=6,
                                      alignment=TA_CENTER,
                                      endDots=' *')
        istyDotsJCJK = ParagraphStyle('istyDotsJ',
                                      parent=styNormalCJK,
                                      firstLineIndent=12,
                                      leftIndent=6,
                                      alignment=TA_JUSTIFY,
                                      endDots=' =')

        # some to test
        stySpaced = ParagraphStyle('spaced',
                                   parent=styNormal,
                                   spaceBefore=12,
                                   spaceAfter=12)

        SA(Paragraph("This is a normal paragraph. " + randomText(), styNormal))
        SA(
            Paragraph("There follows a paragraph with only \"&lt;br/&gt;\"",
                      styNormal))
        SA(Paragraph("<br/>", styNormal))
        SA(
            Paragraph(
                "This has 12 points space before and after, set in the style. "
                + randomText(), stySpaced))
        SA(Paragraph("This is normal. " + randomText(), styNormal))
        SA(
            Paragraph(
                """<para spacebefore="12" spaceafter="12">
            This has 12 points space before and after, set inline with
            XML tag.  It works too.""" + randomText() + "</para>", styNormal))

        SA(Paragraph("This is normal. " + randomText(), styNormal))

        styBackground = ParagraphStyle('MyTitle',
                                       fontName='Helvetica-Bold',
                                       fontSize=24,
                                       leading=28,
                                       textColor=white,
                                       backColor=navy)
        SA(Paragraph("This is a title with a background. ", styBackground))
        SA(
            Paragraph(
                """<para backcolor="pink">This got a background from the para tag</para>""",
                styNormal))
        SA(
            Paragraph(
                """<para>\n\tThis has newlines and tabs on the front but inside the para tag</para>""",
                styNormal))
        SA(
            Paragraph(
                """<para>  This has spaces on the front but inside the para tag</para>""",
                styNormal))
        SA(
            Paragraph(
                """\n\tThis has newlines and tabs on the front but no para tag""",
                styNormal))
        SA(
            Paragraph("""  This has spaces on the front but no para tag""",
                      styNormal))
        SA(
            Paragraph(
                """This has <font color=blue backcolor=pink>blue text with pink background</font> here.""",
                styNormal))
        SA(
            Paragraph(
                """<span color=blue backcolor=pink>&nbsp;Nothing but blue text with pink background.&nbsp;</span>""",
                styNormal))
        SA(Paragraph("""This has <i>italic text</i> here.""", styNormal))
        SA(Paragraph("""This has <b>bold text</b> here.""", styNormal))
        SA(Paragraph("""This has <u>underlined text</u> here.""", styNormal))
        SA(
            Paragraph(
                """This has <font color=blue><u>blue and <font color=red>red</font> underlined text</u></font> here.""",
                styNormal))
        SA(Paragraph("""<u>green underlining</u>""", styGreen))
        SA(
            Paragraph(
                """<u>green <font size="+4"><i>underlining</i></font></u>""",
                styGreen))
        SA(
            Paragraph("""This has m<super>2</super> a superscript.""",
                      styNormal))
        SA(
            Paragraph(
                """This has m<sub>2</sub> a subscript. Like H<sub>2</sub>O!""",
                styNormal))
        SA(
            Paragraph(
                """This has a font change to <font name=Helvetica>Helvetica</font>.""",
                styNormal))
        #This one fails:
        #SA(Paragraph("""This has a font change to <font name=Helvetica-Oblique>Helvetica-Oblique</font>.""", styNormal))
        SA(
            Paragraph(
                """This has a font change to <font name=Helvetica><i>Helvetica in italics</i></font>.""",
                styNormal))

        SA(
            Paragraph(
                '''This one uses upper case tags and has set caseSensitive=0: Here comes <FONT FACE="Helvetica" SIZE="14pt">Helvetica 14</FONT> with <STRONG>strong</STRONG> <EM>emphasis</EM>.''',
                styNormal,
                caseSensitive=0))
        SA(
            Paragraph(
                '''The same as before, but has set not set caseSensitive, thus the tags are ignored: Here comes <FONT FACE="Helvetica" SIZE="14pt">Helvetica 14</FONT> with <STRONG>strong</STRONG> <EM>emphasis</EM>.''',
                styNormal))
        SA(
            Paragraph(
                '''This one uses fonts with size "14pt" and also uses the em and strong tags: Here comes <font face="Helvetica" size="14pt">Helvetica 14</font> with <Strong>strong</Strong> <em>emphasis</em>.''',
                styNormal,
                caseSensitive=0))
        SA(
            Paragraph(
                '''This uses a font size of 3cm: Here comes <font face="Courier" size="3cm">Courier 3cm</font> and normal again.''',
                styNormal,
                caseSensitive=0))
        SA(
            Paragraph(
                '''This is just a very long silly text to see if the <FONT face="Courier">caseSensitive</FONT> flag also works if the paragraph is <EM>very</EM> long. '''
                * 20,
                styNormal,
                caseSensitive=0))

        SA(Indenter("1cm"))
        SA(
            Paragraph(
                "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2'>1.1</bullet>sample bullet default anchor</para>",
                styNormal))
        SA(
            Paragraph(
                "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2'>1.22</bullet>sample bullet default anchor</para>",
                styNormal))
        SA(
            Paragraph(
                "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2' anchor='start'>1.1</bullet>sample bullet start align</para>",
                styNormal))
        SA(
            Paragraph(
                "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2' anchor='start'>1.22</bullet>sample bullet start align</para>",
                styNormal))
        SA(
            Paragraph(
                "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2' anchor='middle'>1.1</bullet>sample bullet middle align</para>",
                styNormal))
        SA(
            Paragraph(
                "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2' anchor='middle'>1.22</bullet>sample bullet middle align</para>",
                styNormal))
        SA(
            Paragraph(
                "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2' anchor='end'>1.1</bullet>sample bullet end align</para>",
                styNormal))
        SA(
            Paragraph(
                "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2' anchor='end'>1.22</bullet>sample bullet end align</para>",
                styNormal))
        SA(
            Paragraph(
                "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2' anchor='numeric'>1.1</bullet>sample bullet numeric align</para>",
                styNormal))
        SA(
            Paragraph(
                "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2' anchor='numeric'>1.22</bullet>sample bullet numeric align</para>",
                styNormal))
        SA(
            Paragraph(
                "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2' anchor='numeric'><span color='red'>1</span><span color='green'>.</span><span color='blue'>3</span></bullet>sample bullet numeric align</para>",
                styNormal))

        SA(
            Paragraph(
                "<para><bullet bulletIndent='-1cm' bulletOffsetY='2'><seq id='s0'/>)</bullet>Indented list bulletOffsetY=2. %s</para>"
                % randomText(), styNormal))
        SA(
            Paragraph(
                "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>"
                % randomText(), styNormal))
        SA(
            Paragraph(
                "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>"
                % randomText(), styNormal))
        SA(Indenter("1cm"))
        SA(
            XPreformatted(
                "<para leftIndent='0.5cm' backcolor=pink><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>",
                styNormal))
        SA(
            XPreformatted(
                "<para leftIndent='0.5cm' backcolor=palegreen><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>",
                styNormal))
        SA(Indenter("-1cm"))
        SA(
            Paragraph(
                "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>"
                % randomText(), styNormal))
        SA(Indenter("-1cm"))
        SA(
            Paragraph(
                "<para>Indented list using seqChain/Format<seqChain order='s0 s1 s2 s3 s4'/><seqReset id='s0'/><seqFormat id='s0' value='1'/><seqFormat id='s1' value='a'/><seqFormat id='s2' value='i'/><seqFormat id='s3' value='A'/><seqFormat id='s4' value='I'/></para>",
                stySpaced))
        SA(Indenter("1cm"))
        SA(
            Paragraph(
                "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>"
                % randomText(), styNormal))
        SA(
            Paragraph(
                "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>"
                % randomText(), styNormal))
        SA(
            Paragraph(
                "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>"
                % randomText(), styNormal))
        SA(Indenter("1cm"))
        SA(
            XPreformatted(
                "<para backcolor=pink boffsety='-3'><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list bulletOffsetY=-3.</para>",
                styNormal))
        SA(
            XPreformatted(
                "<para backcolor=pink><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>",
                styNormal))
        SA(Indenter("-1cm"))
        SA(
            Paragraph(
                "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>"
                % randomText(), styNormal))
        SA(Indenter("1cm"))
        SA(
            XPreformatted(
                "<para backcolor=palegreen><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>",
                styNormal))
        SA(Indenter("1cm"))
        SA(
            XPreformatted(
                "<para><bullet bulletIndent='-1cm'><seq id='s2'/>)</bullet>Indented list. line1</para>",
                styNormal))
        SA(
            XPreformatted(
                "<para><bullet bulletIndent='-1cm'><seq id='s2'/>)</bullet>Indented list. line2</para>",
                styNormal))
        SA(Indenter("-1cm"))
        SA(
            XPreformatted(
                "<para backcolor=palegreen><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>",
                styNormal))
        SA(Indenter("-1cm"))
        SA(Indenter("-1cm"))

        for i in range(2):
            SA(PageBreak())
            SA(
                Paragraph(
                    '''%s dotted paragraphs''' % (i and 'CJK' or 'Normal'),
                    styNormal))
            SA(
                Paragraph('''Simple paragraph with dots''', i and styDotsCJK
                          or styDots))
            SA(
                Paragraph('''Simple indented paragraph with dots''',
                          i and istyDotsCJK or istyDots))
            SA(
                Paragraph('''Simple centred paragraph with stars''',
                          i and styDotsCCJK or styDotsC))
            SA(
                Paragraph('''Simple centred indented paragraph with stars''',
                          i and istyDotsCCJK or istyDotsC))
            SA(
                Paragraph(
                    '''Simple right justified paragraph with pluses, but no pluses''',
                    i and styDotsRCJK or styDotsR))
            SA(
                Paragraph(
                    '''Simple right justified indented paragraph with pluses, but no pluses''',
                    i and istyDotsRCJK or istyDotsR))
            SA(
                Paragraph('''Simple justified paragraph with equals''',
                          i and styDotsJCJK or styDotsJ))
            SA(
                Paragraph(
                    '''Simple justified indented paragraph with equals''',
                    i and istyDotsJCJK or istyDotsJ))
            SA(
                Paragraph('''A longer simple paragraph with dots''',
                          i and styDotsCJK or styDots))
            SA(
                Paragraph('''A longer simple indented paragraph with dots''',
                          i and istyDotsCJK or istyDots))
            SA(
                Paragraph(
                    'A very much' + 50 * ' longer' +
                    ' simple paragraph with dots', i and styDotsCJK
                    or styDots))
            SA(
                Paragraph(
                    'A very much' + 50 * ' longer' +
                    ' simple indented paragraph with dots', i and istyDotsCJK
                    or istyDots))
            SA(
                Paragraph(
                    'A very much' + 50 * ' longer' +
                    ' centred simple paragraph with stars', i and styDotsCCJK
                    or styDotsC))
            SA(
                Paragraph(
                    'A very much' + 50 * ' longer' +
                    ' centred simple indented paragraph with stars',
                    i and istyDotsCCJK or istyDotsC))
            SA(
                Paragraph(
                    'A very much' + 50 * ' longer' +
                    ' right justified simple paragraph with pluses, but no pluses',
                    i and styDotsRCJK or styDotsR))
            SA(
                Paragraph(
                    'A very much' + 50 * ' longer' +
                    ' right justified simple indented paragraph with pluses, but no pluses',
                    i and istyDotsRCJK or istyDotsR))
            SA(
                Paragraph(
                    'A very much' + 50 * ' longer' +
                    ' justified simple paragraph with equals',
                    i and styDotsJCJK or styDotsJ))
            SA(
                Paragraph(
                    'A very much' + 50 * ' longer' +
                    ' justified simple indented paragraph with equals',
                    i and istyDotsJCJK or istyDotsJ))
            SA(
                Paragraph(
                    '''Simple paragraph with dashes that have a dy and a textColor.''',
                    i and styDots1CJK or styDots1))
            SA(
                Paragraph(
                    '''Simple indented paragraph with dashes that have a dy and a textColor.''',
                    i and istyDots1CJK or istyDots1))
            SA(
                Paragraph(
                    '''Complex <font color="green">paragraph</font> with dots''',
                    i and styDotsCJK or styDots))
            SA(
                Paragraph(
                    '''Complex <font color="green">indented paragraph</font> with dots''',
                    i and istyDotsCJK or istyDots))
            SA(
                Paragraph(
                    '''Complex centred <font color="green">paragraph</font> with stars''',
                    i and styDotsCCJK or styDotsC))
            SA(
                Paragraph(
                    '''Complex centred <font color="green">indented paragraph</font> with stars''',
                    i and istyDotsCCJK or istyDotsC))
            SA(
                Paragraph(
                    '''Complex right justfied <font color="green">paragraph</font> with pluses, but no pluses''',
                    i and styDotsRCJK or styDotsR))
            SA(
                Paragraph(
                    '''Complex right justfied <font color="green">indented paragraph</font> with pluses, but no pluses''',
                    i and istyDotsRCJK or istyDotsR))
            SA(
                Paragraph(
                    '''Complex justfied <font color="green">paragraph</font> with equals''',
                    i and styDotsJCJK or styDotsJ))
            SA(
                Paragraph(
                    '''Complex justfied <font color="green">indented paragraph</font> with equals''',
                    i and istyDotsJCJK or istyDotsJ))
            SA(
                Paragraph(
                    '''A longer complex <font color="green">paragraph</font> with dots''',
                    i and styDotsCJK or styDots))
            SA(
                Paragraph(
                    '''A longer complex <font color="green">indented paragraph</font> with dots''',
                    i and istyDotsCJK or istyDots))
            SA(
                Paragraph(
                    'A very much' + 50 * ' longer' +
                    ' complex <font color="green">paragraph</font> with dots',
                    i and styDotsCJK or styDots))
            SA(
                Paragraph(
                    'A very much' + 50 * ' longer' +
                    ' complex <font color="green">indented paragraph</font> with dots',
                    i and istyDotsCJK or istyDots))
            SA(
                Paragraph(
                    '''Complex <font color="green">paragraph</font> with dashes that have a dy and a textColor.''',
                    i and styDots1CJK or styDots1))
            SA(
                Paragraph(
                    '''Complex <font color="green">indented paragraph</font> with dashes that have a dy and a textColor.''',
                    i and istyDots1CJK or istyDots1))
            SA(
                Paragraph(
                    'A very much' + 50 * ' longer' +
                    ' centred complex <font color="green">paragraph</font> with stars',
                    i and styDotsCCJK or styDotsC))
            SA(
                Paragraph(
                    'A very much' + 50 * ' longer' +
                    ' centred complex <font color="green">indented paragraph</font> with stars',
                    i and istyDotsCCJK or istyDotsC))
            SA(
                Paragraph(
                    'A very much' + 50 * ' longer' +
                    ' right justified <font color="green">complex</font> paragraph with pluses, but no pluses',
                    i and styDotsRCJK or styDotsR))
            SA(
                Paragraph(
                    'A very much' + 50 * ' longer' +
                    ' right justified <font color="green">complex</font> indented paragraph with pluses, but no pluses',
                    i and istyDotsRCJK or istyDotsR))
            SA(
                Paragraph(
                    'A very much' + 50 * ' longer' +
                    ' justified complex <font color="green">paragraph</font> with equals',
                    i and styDotsJCJK or styDotsJ))
            SA(
                Paragraph(
                    'A very much' + 50 * ' longer' +
                    ' justified complex <font color="green">indented paragraph</font> with equals',
                    i and istyDotsJCJK or istyDotsJ))

        SA(
            Paragraph(
                '<para>This image has the image data embedded in the src attribute: <img src="DATA:image/gif;base64,R0lGODdhDwAMAIACAAAAAPf/EiwAAAAADwAMAAACHIyPqcvtCl4ENEQzbc3XnjtV2Dd247mBnva0SwEAOw==" /></para>',
                styNormal))
        template = SimpleDocTemplate(outputfile('test_paragraphs.pdf'),
                                     showBoundary=1)
        template.build(story,
                       onFirstPage=myFirstPage,
                       onLaterPages=myLaterPages)
示例#21
0
def Listado004Distrital(ubigeos, WorkSpace, VW_DISTRITO, SEGM_R_RUTAS, SEGM_R_CCPPRUTAS, SEGM_R_AER, EscudoNacional, LogoInei, tipo):

    #   CREADO ESTILOS DE TEXTO
    h1 = PS(
        name='Heading1',
        fontSize=7,
        leading=8
    )

    h3 = PS(
        name='Normal',
        fontSize=6.5,
        leading=10,
        alignment=TA_CENTER
    )
    h4 = PS(
        name='Normal',
        fontSize=6.5,
        leading=10,
        alignment=TA_LEFT
    )

    h5 = PS(
        name='Heading1',
        fontSize=7,
        leading=8,
        alignment=TA_RIGHT
    )

    h_sub_tile = PS(
        name='Heading1',
        fontSize=10,
        leading=14,
        alignment=TA_CENTER
    )
    h_sub_tile_2 = PS(
        name='Heading1',
        fontSize=11,
        leading=14,
        alignment=TA_CENTER
    )


    for ubigeo in [x for x in arcpy.da.SearchCursor(VW_DISTRITO, ["UBIGEO", "DEPARTAMENTO", "PROVINCIA", "DISTRITO"], "UBIGEO = '{}'".format(ubigeos))]:

        departamento = ubigeo[1]
        coddep = ubigeo[0][0:2]
        provincia = ubigeo[2]
        codprov = ubigeo[0][2:4]
        distrito = ubigeo[3]
        coddist = ubigeo[0][4:6]
        if tipo == 1:
            scr_tmp = [x[0] for x in arcpy.da.SearchCursor(SEGM_R_RUTAS, ["SCR"], "UBIGEO = '{}'".format(ubigeo[0]))]
            scr = u'{} - {}'.format(min(scr_tmp), max(scr_tmp))
        else:
            scr = u''


        aerini = min([x[0] for x in arcpy.da.SearchCursor(SEGM_R_AER, ["AER_INI"], "UBIGEO = '{}'".format(ubigeo[0]))])
        aerfin = max([x[0] for x in arcpy.da.SearchCursor(SEGM_R_AER, ["AER_FIN"], "UBIGEO = '{}'".format(ubigeo[0]))])
        viviendas = sum([x[0] for x in arcpy.da.SearchCursor(SEGM_R_RUTAS, ["N_VIV_RUTA"], "UBIGEO = '{}'".format(ubigeo[0]))])


        #   LISTA QUE CONTIENE LOS ELEMENTOS A GRAFICAR EN EL PDF
        
        Elementos = []


        #   AGREGANDO IMAGENES, TITULOS Y SUBTITULOS

        if tipo == 1:
            Titulo = Paragraph(u'CENSOS NACIONALES 2017: XII DE POBLACIÓN, VII DE VIVIENDA Y III DE COMUNIDADES INDÍGENAS', h_sub_tile)
            Titulo2 = Paragraph(u'III Censo de Comunidades Nativas y I Censo de Comunidades Campesinas', h_sub_tile)
            SubTitulo = Paragraph(u'<strong>MARCO DE SECCIONES CENSALES, ÁREAS DE EMPADRONAMIENTO RURAL Y CENTROS POBLADOS DEL DISTRITO</strong>', h_sub_tile_2)
        else:
            Titulo = Paragraph(u'CENSO DE LAS ÁREAS AFECTADAS POR ELFENÓMENO DE', h_sub_tile)
            Titulo2 = Paragraph(u'EL NIÑO COSTERO', h_sub_tile)
            SubTitulo = Paragraph(u'<strong>MARCO DE ÁREAS DE EMPADRONAMIENTO RURAL Y CENTROS POBLADOS DEL DISTRITO</strong>', h_sub_tile_2)


        CabeceraPrincipal = [[Titulo, '', ''],
                             [Image(EscudoNacional, width=50, height=50), Titulo2,
                              Image(LogoInei, width=50, height=50)],
                             ['', SubTitulo, '']]

        Tabla0 = Table(CabeceraPrincipal, colWidths=[2 * cm, 14 * cm, 2 * cm])

        Tabla0.setStyle(TableStyle([
            ('GRID', (0, 0), (-1, -1), 1, colors.white),
            ('SPAN', (0, 1), (0, 2)),
            ('SPAN', (2, 1), (2, 2)),
            ('SPAN', (0, 0), (2, 0)),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE')
        ]))

        Elementos.append(Tabla0)
        Elementos.append(Spacer(0,10))


        #   CREACION DE LAS TABLAS PARA LA ORGANIZACION DEL TEXTO
        #   Se debe cargar la informacion en aquellos espacios donde se encuentra el texto 'R'

        Filas = [
                ['', '', '', '', Paragraph(u'<b>Doc.CPV.03.159A</b>', h5),''],
                [Paragraph('<b>A. UBICACIÓN GEOGRÁFICA</b>', h1), '', '', '',Paragraph('<b>B. UBICACIÓN CENSAL</b>', h1), ''],
                [Paragraph('<b>DEPARTAMENTO</b>', h1), u'{}'.format(coddep), u'{}'.format(departamento), '',Paragraph(u'<b>SECCIÓN Nº</b>', h1), scr],
                [Paragraph('<b>PROVINCIA</b>', h1), u'{}'.format(codprov), u'{}'.format(provincia), '', Paragraph(u'<b>AER Nº</b>', h1), 'DEL {} AL {}'.format(aerini, aerfin)],
                [Paragraph('<b>DISTRITO</b>', h1), u'{}'.format(coddist), u'{}'.format(distrito), '', '',''],
                ['', '','', '',Paragraph('<b>C. TOTAL DE VIVIENDAS DEL DISTRITO.</b>', h1), '{}'.format(viviendas)]
                ]
    

        #   Permite el ajuste del ancho de la tabla

        Tabla = Table(Filas, colWidths=[3.7 * cm, 1 * cm, 7.1 * cm, 0.3 * cm, 4.5 * cm, 2.2 * cm])


        #   Se cargan los estilos, como bordes, alineaciones, fondos, etc

        Tabla.setStyle(TableStyle([
                    ('FONTSIZE', (0, 0), (-1, -1), 7),
                    ('TEXTCOLOR', (0, 0), (5, 0), colors.black),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('ALIGN', (5, 2), (5, 5), 'CENTER'),
                    ('ALIGN', (1, 2), (1, 4), 'CENTER'),
                    ('GRID', (0, 1), (2, 4), 1, colors.black),
                    ('GRID', (4, 5), (5, 5), 1, colors.black),
                    ('GRID', (4, 1), (5, 3), 1, colors.black),
                    ('GRID', (4, 3), (5, 3), 1, colors.black),
                    ('SPAN', (0, 1), (2, 1)),
                    ('SPAN', (4, 1), (5, 1)),
                    ('SPAN', (4, 0), (5, 0)),
                    ('BACKGROUND', (0, 1), (2, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)),
                    ('BACKGROUND', (0, 2), (0, 4), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)),
                    ('BACKGROUND', (4, 1), (4, 3), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)),
                    ('BACKGROUND', (4, 5), (4, 5), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)),
                    ('BACKGROUND', (4, 1), (5, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255))
                    ]))


        #   AGREGANDO LAS TABLAS A LA LISTA DE ELEMENTOS DEL PDF

        Elementos.append(Tabla)
        Elementos.append(Spacer(0,10))


        #   AGREGANDO CABECERA N° 2

        Filas2 = [
            [Paragraph(e, h3) for e in [u"<strong>D. INFORMACIÓN DE LAS SECCIONES CENSALES Y ÁREAS DE EMPADRONAMIENTO DEL DISTRITO</strong>", "", "", "","", "", "", "", ""]],
            [Paragraph(e, h3) for e in [u"<strong>SECCIÓN Nº</strong>", u"<strong>AER N°</strong>", "", u"<strong>RUTA</strong>", u"<strong>EMP</strong>", u"<strong>CENTRO POBLADO</strong>", "", "",u"<strong>N° ESTIMADO DE VIVIENDAS</strong>"]],
            [Paragraph(e, h3) for e in ["", u"<strong>INICIAL</strong>", u"<strong>FINAL</strong>", "", "", u"<strong>CÓDIGO</strong>", u"<strong>NOMBRE</strong>", u"<strong>CATEGORÍA</strong>", ""]]
            ]
        
        Tabla2 = Table(Filas2,
                  colWidths = [1.5 * cm, 1.5 * cm, 1.5 * cm, 1.5 * cm, 1.5 * cm, 1.5 * cm, 5.5 * cm, 2 * cm, 2.3 * cm])

        Tabla2.setStyle(TableStyle(
            [
                ('GRID', (0, 0), (-1, -1), 1, colors.black),
                ('VALIGN', (0, 0), (-1, -1), 'CENTER'),
                ('FONTSIZE', (0, 0), (-1, -1), 7),
                ('BACKGROUND', (0, 0), (-1, -1), colors.Color(220.0/255, 220.0/255, 220.0/255)),
                ('SPAN', (0, 1), (0, 2)),
                ('SPAN', (0, 0), (8, 0)),
                ('SPAN', (1, 1), (2, 1)),
                ('SPAN', (3, 1), (3, 2)),
                ('SPAN', (4, 1), (4, 2)),
                ('SPAN', (5, 1), (7, 1)),
                ('SPAN', (8, 1), (8, 2)),
            ]
        ))

        Elementos.append(Tabla2)


        #CUERPO QUE CONTIENE LOS LA INFORMACION A MOSTRAR

        nrows = len([x[0] for x in arcpy.da.SearchCursor(SEGM_R_CCPPRUTAS, ["CODCCPP"], "UBIGEO = '{}'".format(ubigeo[0]))])
        cursor = [x for x in arcpy.da.SearchCursor(SEGM_R_CCPPRUTAS, ["SCR", "AER_INI", "AER_FIN", "RUTA", "CODCCPP", "NOMCCPP", "CAT_CCPP", "VIV_CCPP", "OR_CCPP", "IDRUTA"] , "UBIGEO = '{}'".format(ubigeo[0]))]
        cursor.sort(key = lambda n:(n[0], n[3], n[-1]))
        
        if nrows > 26:

            SeccionesRegistros = registros(nrows)
            
            SeccionesRegistros.append((0, 26))

            SeccionesRegistros.sort(key = lambda n:n[0])

            for rangos in SeccionesRegistros:
                
                for ccpp in cursor[rangos[0]:rangos[1]]:
                    scr = ccpp[0] if tipo == 1 else u''
                    aeriniccpp = ccpp[1]
                    aerfinccpp = ccpp[2]
                    rutaccpp = ccpp[3]
                    emp = empadronadorEtiqueta(ccpp[9])
                    codccpp = ccpp[4]
                    nomccpp = ccpp[5]
                    categoriaccpp = ccpp[6]
                    numviv = ccpp[7]
                    
                    registrosdist = [[scr, u'{}'.format(aeriniccpp), u'{}'.format(aerfinccpp), u'{}'.format(rutaccpp), u'{}'.format(emp), u'{}'.format(codccpp), Paragraph(u'{}'.format(nomccpp), h4), Paragraph(u'{}'.format(categoriaccpp), h4), u'{}'.format(numviv)]]

                    RegistrosIngresados = Table(registrosdist,
                              colWidths = [1.5 * cm, 1.5 * cm, 1.5 * cm, 1.5 * cm, 1.5 * cm, 1.5 * cm, 5.5 * cm, 2 * cm, 2.3 * cm],
                              rowHeights=[0.7 * cm])
                    
                    RegistrosIngresados.setStyle(TableStyle(
                        [
                            ('GRID', (0, 0), (-1, -1), 1, colors.black),
                            ('FONTSIZE', (0, 0), (-1, -1), 7),
                            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                            ('ALIGN', (0, 0), (5, 0), 'CENTER'),
                        ]
                    ))
                    Elementos.append(RegistrosIngresados)
                Elementos.append(PageBreak())
                Elementos.append(Tabla2)
            del Elementos[-1]
            del Elementos[-1] 
        else:
            for ccpp in cursor:
                scr = ccpp[0] if tipo == 1 else u''
                aeriniccpp = ccpp[1]
                aerfinccpp = ccpp[2]
                rutaccpp = ccpp[3]
                emp = empadronadorEtiqueta(ccpp[9])
                codccpp = ccpp[4]
                nomccpp = ccpp[5]
                categoriaccpp = ccpp[6]
                numviv = ccpp[7]

                registrosdist = [[scr, u'{}'.format(aeriniccpp), u'{}'.format(aerfinccpp), u'{}'.format(rutaccpp), u'{}'.format(emp), u'{}'.format(codccpp), Paragraph(u'{}'.format(nomccpp), h4), Paragraph(u'{}'.format(categoriaccpp), h4), u'{}'.format(numviv)]]

                RegistrosIngresados = Table(registrosdist,
                          colWidths = [1.5 * cm, 1.5 * cm, 1.5 * cm, 1.5 * cm, 1.5 * cm, 1.5 * cm, 5.5 * cm, 2 * cm, 2.3 * cm],
                          rowHeights=[0.7 * cm])
                
                RegistrosIngresados.setStyle(TableStyle(
                    [
                        ('GRID', (0, 0), (-1, -1), 1, colors.black),
                        ('FONTSIZE', (0, 0), (-1, -1), 7),
                        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                        ('ALIGN', (0, 0), (5, 0), 'CENTER'),
                    ]
                ))
                Elementos.append(RegistrosIngresados)

        #   SE DETERMINAN LAS CARACTERISTICAS DEL PDF (RUTA DE ALMACENAJE, TAMAÑO DE LA HOJA, ETC)
        

        if tipo == 1:
            PathPDF = r"{}\Rural\{}\{}.pdf".format(WorkSpace, ubigeo[0], ubigeo[0])
        else:
            PathPDF = r"{}\Rural_FEN\{}\{}.pdf".format(WorkSpace, ubigeo[0], ubigeo[0])

        print PathPDF

        pdfsec = SimpleDocTemplate(PathPDF, pagesize=A4, rightMargin=65, leftMargin=65, topMargin=0.5*cm, bottomMargin=0.5*cm,)

        #   GENERACION DEL PDF FISICO

        pdfsec.build(Elementos)


    #   IMPRESION DE FINALIZADO
    finalizado = "Finalizado"
    return finalizado
示例#22
0
 def add_page_break(self):
     '''添加分页符'''
     self.__content.append(PageBreak())
示例#23
0
	def draw_canvas(self, page_count):
		page = 'Page {0} of {1}'.format(self._pageNumber, page_count)
		x = 128
		self.saveState()
		pdfmetrics.registerFont(TTFont('OpenSans', '/usr/share/fonts/OpenSans-Regular.ttf'))
		self.setFont('OpenSans', 10)
		self.setStrokeColorRGB(0, 0, 0)
		self.setLineWidth(0.5)
		self.drawCentredString(120, letter[1] - 30, 'Network Device Report')
		self.drawString(letter[0] - 120, letter[1] - 30, page)	
		self.line(66, letter[1] - 40, letter[0] - 66, letter[1] - 40)
		self.line(66, 78, letter[0] - 66, 78)
		#self.drawCentredString(letter[0] / 2, 65, page)	
		self.drawImage('logo-blue.jpg', letter[0] - 175, 25, height=50, width=120)
		#self.drawString(letter[0]-x, 25, page)
		self.restoreState()


styles = getSampleStyleSheet()
elements = []
#elements.append(Image('logo-blue.png', height=103, 250))
#elements.append(Paragraph("Hello"))
#elements.append(Paragraph("World"))
elements.append(PageBreak())
elements.append(PageBreak())
elements.append(PageBreak())
#elements.append(Paragraph("You are in page 2"))

doc = SimpleDocTemplate("device_report.pdf", pagesize=letter)
doc.multiBuild(elements, canvasmaker=FooterCanvas)
示例#24
0
 def __init__(self, file_path):
     self.__register_font()
     self.__doc = myDocTemplate(file_path)
     self.__title = "JY.zenist.song PDF实例"
     self.__page_info = "JY.zenist.song"
     self.__content = [PageBreak()]
示例#25
0
def xnotmotherpdf(request, lid, xlid):

    filename = lid + '.pdf'
    dirfile = "/tmp/" + filename

    libname = Library.objects.get(lid=lid).name

    doc = SimpleDocTemplate(filename="{}".format(dirfile),
                            pagesize=landscape(A4))
    elements = []

    #For the lid identified library, getting ressources whose the resulting \
    #collection has been entirely completed and may consequently be edited.
    #Trick : These ressources have two instructions with name = 'checker' :
    #This is like "tobeedited" (see below)

    l = ItemRecord.objects.filter(lid=lid).exclude(rank=1).exclude(rank=0)

    #Initializing a list of ressources to edit :
    resslist = []

    for e in l:
        nl = Instruction.objects.filter(sid=e.sid)
        kd = nl.filter(name="checker")
        if len(kd) == 2 and Instruction.objects.filter(
                sid=e.sid, name=Library.objects.get(lid=xlid)):
            resslist.append(e)

    for r in resslist:

        # Draw things on the PDF. Here's where the PDF generation happens.
        # See the ReportLab documentation for the full list of functionality.
        title = ItemRecord.objects.get(sid=r.sid, lid=lid).title
        sid = ItemRecord.objects.get(sid=r.sid, lid=lid).sid
        cn = ItemRecord.objects.get(sid=sid, lid=lid).cn
        issn = ItemRecord.objects.get(sid=r.sid, lid=lid).issn
        pubhist = ItemRecord.objects.get(sid=r.sid, lid=lid).pubhist
        instructions = Instruction.objects.filter(sid=r.sid).order_by('line')
        properinstructions = Instruction.objects.filter(sid=r.sid,
                                                        name=libname)
        otherinstructions = Instruction.objects.filter(sid=r.sid,
                                                       oname=libname)
        libinstructions = properinstructions.union(otherinstructions).order_by(
            'line')
        controlbd = Instruction.objects.get(sid=r.sid,
                                            bound='x',
                                            name='checker').descr
        controlnotbd = Instruction.objects.exclude(bound='x').get(
            sid=r.sid, name='checker').descr
        mothercollection = Library.objects.get(
            lid=ItemRecord.objects.get(sid=r.sid, rank=1).lid).name

        datap = [
            [_('Projet'), project],
            [_("Titre"), Paragraph(title, styles['Normal'])],
            [
                _("Collection"),
                str(libname + "    ----->    " + _('cote') + " : " + cn)
            ],
        ]

        tp = Table(datap)

        table_stylep = TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ])

        tp.setStyle(table_stylep)

        elements.append(tp)

        datas = [[
            str(_('issn') + " : " + issn),
            str(_('ppn') + " : " + sid),
            str(_('historique de la publication') + " : " + pubhist)
        ]]

        ts = Table(datas)

        table_styles = TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ])

        ts.setStyle(table_styles)

        elements.append(ts)

        datacoll = []

        for e in ItemRecord.objects.filter(sid=sid).order_by("rank"):
            if e.rank == 1:
                datacoll.append([
                    e.rank,
                    Library.objects.get(lid=e.lid).name,
                    _("collection mère")
                ])
            elif e.rank == 0:
                datacoll.append(
                    [e.rank,
                     Library.objects.get(lid=e.lid).name, e.excl])
            else:
                datacoll.append([
                    e.rank,
                    Library.objects.get(lid=e.lid).name,
                    _("a pris part")
                ])

        tcoll = Table(datacoll)

        table_stylecoll = TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ])

        tcoll.setStyle(table_stylecoll)

        elements.append(tcoll)

        data = [["", "", "", "", "", "", ""],
                [
                    '#',
                    _('bibliothèque'),
                    _('relié ?'),
                    _('bib. remédiée'),
                    _('segment'),
                    _('exception'),
                    _('améliorable')
                ]]
        Table(data,
              colWidths=None,
              rowHeights=None,
              style=None,
              splitByRow=1,
              repeatRows=0,
              repeatCols=0,
              rowSplitRange=None,
              spaceBefore=None,
              spaceAfter=None)
        for i in instructions:
            data.append([
                i.line, i.name, i.bound, i.oname, i.descr,
                Paragraph(i.exc, styles['Normal']),
                Paragraph(i.degr, styles['Normal'])
            ])

        t = Table(data)

        table_style = TableStyle([
            ('ALIGN', (1, 1), (6, 1), 'CENTER'),
            ('INNERGRID', (0, 1), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 1), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ])
        k = 1
        for i in libinstructions:
            row = i.line + 1
            k += 1  #row number
            table_style.add('TEXTCOLOR', (0, row), (6, row), colors.red)
        table_style.add('ALIGN', (0, 1), (-7, -1), 'CENTER')
        table_style.add('ALIGN', (0, 2), (-5, -1), 'CENTER')
        table_style.add('ALIGN', (1, 1), (-6, -1), 'LEFT')

        t.setStyle(table_style)

        elements.append(t)

        elements.append(PageBreak())

    doc.build(elements)

    fs = FileSystemStorage("/tmp")
    with fs.open(filename) as pdf:
        response = HttpResponse(pdf, content_type='application/pdf')
        response['Content-Disposition'] = 'inline; filename="{}"'.format(
            filename)
        return response

    return response
def create_final_pdf(results: ProcessingResults, output_file_handle):
    styles = getSampleStyleSheet()
    doc = BaseDocTemplate(
        output_file_handle,
        pagesize=letter,
        rightMargin=_PDF.MARGIN,
        leftMargin=_PDF.MARGIN,
        topMargin=2 * _PDF.MARGIN,
        bottomMargin=_PDF.MARGIN,
    )

    portrait_frame = Frame(_PDF.MARGIN,
                           _PDF.MARGIN,
                           doc.width,
                           doc.height,
                           id="portrait_frame")
    landscape_frame = Frame(0, 0, letter[1], letter[0], id="landscape_frame")

    header_style = ParagraphStyle("header",
                                  parent=styles["BodyText"],
                                  fontSize=16,
                                  alignment=TA_CENTER)
    header_text = results.combined_barcode

    watermark_style = ParagraphStyle(
        "footer",
        parent=styles["Heading1"],
        textColor=colors.pink,
        fontSize=36,
        alpha=0.5,
    )

    footer_style = ParagraphStyle("footer",
                                  parent=styles["BodyText"],
                                  textColor=colors.white)
    footer_text = f"Processed by {get_git_info()}"

    page_template_args = [
        make_header_fn(header_text, header_style),
        make_footer_fn(footer_text, footer_style),
    ]
    if results.experimental_run:
        page_template_args.append(
            make_watermark_fn("EXPERIMENTAL! DO NOT REPORT!", watermark_style))
    elif results.invalid_accessions():
        page_template_args.append(
            make_watermark_fn("INVALID ACCESSIONS! DO NOT REPORT!",
                              watermark_style))

    doc.addPageTemplates([
        PageTemplate(
            id="portrait",
            frames=portrait_frame,
            onPageEnd=make_chain_fn(*page_template_args),
        ),
        PageTemplate(
            id="landscape",
            frames=landscape_frame,
            pagesize=landscape(letter),
            onPageEnd=make_chain_fn(*page_template_args),
        ),
    ])

    results_table_style = TableStyle([
        ("SPAN", (0, 0), (1, 0)),  # accession gets two columns
        ("FONT", (0, 0), (-1, 0), styles["Heading1"].fontName),  # bold header
        ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
        ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black),
        ("ALIGN", (0, 0), (-1, -1), "CENTER"),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
    ])

    controls_table_style = TableStyle([
        ("FONT", (0, 0), (-1, 0), styles["Heading1"].fontName),  # bold header
        ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
        ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black),
        ("ALIGN", (0, 0), (-1, -1), "CENTER"),
        ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
    ])

    results_data = results.protocol.format_header_for_reports(
        start=["Accession", "", "Well", "Call"])

    call_column = results_data[0].index("Call")
    first_ct_column = call_column + 1  # start of cts data

    controls_data = results.protocol.format_header_for_reports(
        start=["Control Type", "Well", "Call"])

    row_heights = [_PDF.HEADER_ROW_HEIGHT]

    notable_wells = defaultdict(list)

    for col in COLS_96:
        for row in ROWS_96:
            well_id = f"{row}{col}"
            well_results = results.get_well_results(well_id)

            gene_cts = [
                well_results.format_ct(gene) or "ND"
                for gene in results.protocol.gene_list
            ]

            row_data = [
                "",
                well_results.accession,
                well_id,
                well_results.call.needs_review,
                *gene_cts,
            ]

            if well_results.control_type is not None:
                row_data[0] = "Control"
                row_heights.append(_PDF.CONTROL_ROW_HEIGHT)

                control_type = well_results.control_type
                control_len = len(controls_data)

                controls_row = [
                    well_results.control_type,
                    well_id,
                    well_results.call,
                    *gene_cts,
                ]
                controls_data.append(controls_row)

                if well_results.call != Call.PASS:
                    controls_table_style.add(
                        "BOX",
                        (0, control_len),
                        (-1, control_len + 1),
                        1.5,
                        colors.red,
                    )
                    controls_table_style.add(
                        "TEXTCOLOR",
                        (2, control_len),
                        (2, control_len),
                        colors.red,
                    )
                    detailed_status = results.protocol.get_failure_details(
                        control_type)

                    controls_data.append([detailed_status])

                    controls_table_style.add("SPAN", (0, control_len + 1),
                                             (-1, control_len + 1))
            elif len(well_results.accession
                     ) == 0 or well_results.accession == "nan":
                row_data[1] = ""
                row_heights.append(_PDF.EMPTY_ROW_HEIGHT)
            else:
                # a well with a real accession in it
                row_data[0] = Code128(
                    well_results.accession,
                    barHeight=_PDF.BARCODE_HEIGHT,
                    barWidth=_PDF.BARCODE_WIDTH,
                )
                row_heights.append(_PDF.ACCESSION_ROW_HEIGHT)

                if well_results.call.is_positive or well_results.call.rerun:
                    notable_wells[well_results.call].append(
                        f"{well_results.accession} ({well_id})")

            for j, ct in enumerate(gene_cts):
                if ct == "ND":
                    results_table_style.add(
                        "TEXTCOLOR",
                        (j + first_ct_column, len(results_data)),
                        (j + first_ct_column, len(results_data)),
                        colors.darkgrey,
                    )

            if well_results.call in _PDF.RESULTS_COLOR_CODE:
                results_table_style.add(
                    "TEXTCOLOR",
                    (call_column, len(results_data)),
                    (call_column, len(results_data)),
                    _PDF.RESULTS_COLOR_CODE[well_results.call],
                )

            results_data.append(row_data)

    results_table = Table(results_data,
                          rowHeights=row_heights,
                          repeatRows=1,
                          style=results_table_style)

    controls_table = Table(controls_data,
                           spaceAfter=0.25 * inch,
                           style=controls_table_style)

    metadata_table = format_metadata_table(results, styles)

    header_table_style = TableStyle([("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
                                     ("ALIGN", (0, 0), (-1, -1), "LEFT")])

    logo_table = Table(
        [(_PDF.CZB_LOGO, _PDF.CZI_LOGO), (_PDF.UCSF_LOGO, _PDF.CA_LOGO)],
        colWidths=1 * inch,
    )
    header_table = Table(
        [(logo_table, Paragraph("CLIAHUB - Result Report", styles["Heading1"]))
         ],
        colWidths=[1.75 * inch, 6 * inch],
        style=header_table_style,
    )

    story = [
        header_table,
        metadata_table,
        Paragraph("Controls", styles["Heading1"]),
        controls_table,
        Paragraph("Notes", styles["Heading1"]),
        format_notes(
            results.bravo_metadata.rna_description,
            results.bravo_metadata.qpcr_description,
            results.bravo_metadata.sample_source,
            notable_wells,
            styles,
        ),
        NextPageTemplate("landscape"),  # switching to landscape for next two
        PageBreak(),
        Paragraph(f"{results.combined_barcode} - Plate Map", styles["Title"]),
        create_96_plate_map(results),
        PageBreak(),
        Paragraph(f"{results.combined_barcode} - Ct Curves", styles["Title"]),
        format_ct_curves(results),
        NextPageTemplate("portrait"),  # back to portrait
        PageBreak(),
        Paragraph("Results", styles["Heading1"]),
        results_table,
        PageBreak(),
        Paragraph("Internal Notes", styles["Heading1"]),
        format_internal_notes(results, styles),
        NextPageTemplate("landscape"),  # landscape for background plots
        *format_background_ct_curves(results, styles),
    ]

    # force a 1.4 PDF because that's the minimum to support transparency.
    def canvasmaker(*args, **kwargs):
        return Canvas(*args, pdfVersion=(1, 4), **kwargs)

    doc.build(story, canvasmaker=canvasmaker)
示例#27
0
def users_passwords_to_pdf(pdf):
    """
    Create access data sheets for all users as PDF.
    """
    users_pdf_wlan_ssid = config["users_pdf_wlan_ssid"] or "-"
    users_pdf_wlan_password = config["users_pdf_wlan_password"] or "-"
    users_pdf_wlan_encryption = config["users_pdf_wlan_encryption"] or "-"
    users_pdf_url = config["users_pdf_url"] or "-"
    users_pdf_welcometitle = config["users_pdf_welcometitle"]
    users_pdf_welcometext = config["users_pdf_welcometext"]

    if config['users_sort_users_by_first_name']:
        sort = 'first_name'
    else:
        sort = 'last_name'
    qrcode_size = 2 * cm
    # qrcode for system url
    qrcode_url = QrCodeWidget(users_pdf_url)
    qrcode_url.barHeight = qrcode_size
    qrcode_url.barWidth = qrcode_size
    qrcode_url.barBorder = 0
    qrcode_url_draw = Drawing(45, 45)
    qrcode_url_draw.add(qrcode_url)
    # qrcode for wlan
    text = "WIFI:S:%s;T:%s;P:%s;;" % (users_pdf_wlan_ssid,
                                      users_pdf_wlan_encryption,
                                      users_pdf_wlan_password)
    qrcode_wlan = QrCodeWidget(text)
    qrcode_wlan.barHeight = qrcode_size
    qrcode_wlan.barWidth = qrcode_size
    qrcode_wlan.barBorder = 0
    qrcode_wlan_draw = Drawing(45, 45)
    qrcode_wlan_draw.add(qrcode_wlan)

    for user in User.objects.all().order_by(sort):
        pdf.append(Paragraph(escape(user.get_full_name()), stylesheet['h1']))
        pdf.append(Paragraph(escape(user.number), stylesheet['h3']))
        pdf.append(Spacer(0, 1 * cm))
        data = []
        # WLAN access data
        cell = []
        cell.append(Paragraph(_("WLAN access data"), stylesheet['h2']))
        cell.append(
            Paragraph("%s:" % _("WLAN name (SSID)"), stylesheet['formfield']))
        cell.append(
            Paragraph(escape(users_pdf_wlan_ssid),
                      stylesheet['formfield_value']))
        cell.append(
            Paragraph("%s:" % _("WLAN password"), stylesheet['formfield']))
        cell.append(
            Paragraph(escape(users_pdf_wlan_password),
                      stylesheet['formfield_value']))
        cell.append(
            Paragraph("%s:" % _("WLAN encryption"), stylesheet['formfield']))
        cell.append(
            Paragraph(escape(users_pdf_wlan_encryption),
                      stylesheet['formfield_value']))
        cell.append(Spacer(0, 0.5 * cm))
        # OpenSlides access data
        cell2 = []
        cell2.append(Paragraph(_("OpenSlides access data"), stylesheet['h2']))
        cell2.append(Paragraph("%s:" % _("Username"), stylesheet['formfield']))
        cell2.append(
            Paragraph(escape(user.username), stylesheet['formfield_value']))
        cell2.append(
            Paragraph("%s:" % _("Initial password"), stylesheet['formfield']))
        cell2.append(
            Paragraph(escape(user.default_password),
                      stylesheet['formfield_value']))
        cell2.append(Paragraph("URL:", stylesheet['formfield']))
        cell2.append(
            Paragraph(escape(users_pdf_url), stylesheet['formfield_value']))
        data.append([cell, cell2])
        # QRCodes
        cell = []
        if users_pdf_wlan_ssid != "-" and users_pdf_wlan_encryption != "-":
            cell.append(qrcode_wlan_draw)
            cell.append(
                Paragraph(_("Scan this QRCode to connect WLAN."),
                          stylesheet['qrcode_comment']))
        cell2 = []
        if users_pdf_url != "-":
            cell2.append(qrcode_url_draw)
            cell2.append(
                Paragraph(_("Scan this QRCode to open URL."),
                          stylesheet['qrcode_comment']))
        data.append([cell, cell2])
        # build table
        table = Table(data)
        table._argW[0] = 8 * cm
        table._argW[1] = 8 * cm
        table.setStyle(TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')]))
        pdf.append(table)
        pdf.append(Spacer(0, 2 * cm))

        # welcome title and text
        pdf.append(Paragraph(escape(users_pdf_welcometitle), stylesheet['h2']))
        pdf.append(
            Paragraph(
                escape(users_pdf_welcometext).replace('\r\n', '<br/>'),
                stylesheet['Paragraph12']))
        pdf.append(PageBreak())
    return pdf
    def __init__(self, report: InterestTransferListReport, year: int,
                 today: str):
        self.snippets = get_custom_texts()
        self.buffer = io.BytesIO()
        self.today = today
        story = []

        self._setup_styles()

        doc = SimpleDocTemplate(self.buffer, pagesize=A4)
        doc.leftMargin = 1.5 * cm
        doc.rightMargin = 1.5 * cm
        doc.topMargin = 1.0 * cm
        doc.bottomMargin = 1.5 * cm

        for data in report.per_contract_data:
            story.extend(self._header(data))

            story.append(Spacer(1, 1.0 * cm))
            story.append(
                Paragraph(
                    f"Kontostand Direktkreditvertrag Nr. {data.contract.number}",
                    self.styleH2))

            story.append(Spacer(1, 1.0 * cm))
            story.append(
                Paragraph(f"Guten Tag {data.contract.contact.name}, ",
                          self.styleN))

            story.append(Spacer(1, 0.3 * cm))
            story.append(
                Paragraph((
                    f"der Kontostand des Direktkreditvertrags Nr. {data.contract.number} beträgt heute, "
                    f" am {today} {euro(data.contract.balance)}. "),
                          self.styleN))
            story.append(
                Paragraph(
                    f"Die Zinsen für das Jahr {year} berechnen sich wie folgt:",
                    self.styleN))
            story.append(Spacer(1, 0.3 * cm))
            story.append(interest_year_table(data.interest_rows, narrow=True))
            story.append(Spacer(1, 0.3 * cm))
            story.append(
                Paragraph(f"<b>Zinsen {year}:</b> {euro(data.interest)}",
                          self.styleN))
            story.append(Spacer(1, 0.5 * cm))
            story.append(
                Paragraph((
                    "Wir werden die Zinsen in den nächsten Tagen auf das im Vertrag angegebene Konto "
                    "überweisen. Bitte beachten Sie, dass Sie sich selbst um die Abführung von "
                    "Kapitalertragssteuer und Solidaritätszuschlag kümmern sollten, da wir das nicht "
                    "übernehmen können. "), self.styleN))
            story.append(Spacer(1, 0.5 * cm))
            story.append(Paragraph("Vielen Dank!", self.styleN))
            story.append(Spacer(1, 1.5 * cm))
            story.append(Paragraph("Mit freundlichen Grüßen", self.styleN))
            story.append(Spacer(1, 1.0 * cm))
            story.append(Paragraph(self.snippets['your_name'], self.styleN))
            story.append(
                Paragraph(f"für die {self.snippets['gmbh_name']}",
                          self.styleN))
            story.append(Spacer(1, 0.3 * cm))

            story.append(PageBreak())

        doc.build(story,
                  onFirstPage=self._draw_footer,
                  onLaterPages=self._draw_footer)
        self.buffer.seek(0)
示例#29
0
 def add_page_break(self, num: int = 1):
     for _ in range(num):
         self._text.append(PageBreak())
示例#30
0
def form_04(request_data):
    """
    Форма 030/у - контрольная карта диспансерного учета
    """
    reg_dipensary = DispensaryReg.objects.get(pk=request_data["reg_pk"])
    ind_card = reg_dipensary.card
    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=25 * mm, rightMargin=5 * mm, topMargin=6 * mm, bottomMargin=6 * mm, allowSplitting=1, title="Форма {}".format("025/у"))
    doc = SimpleDocTemplate(buffer,
                            pagesize=landscape(A5),
                            leftMargin=25 * mm,
                            rightMargin=5 * mm,
                            topMargin=6 * mm,
                            bottomMargin=6 * mm,
                            allowSplitting=1,
                            title="Форма {}".format("030/у"))
    width, height = portrait(A4)
    styleSheet = getSampleStyleSheet()
    style = styleSheet["Normal"]
    style.fontName = "PTAstraSerifReg"
    style.fontSize = 10
    style.leading = 12
    style.spaceAfter = 0.5 * mm
    styleBold = deepcopy(style)
    styleBold.fontName = "PTAstraSerifBold"
    styleCenter = deepcopy(style)
    styleCenter.alignment = TA_CENTER
    styleCenter.fontSize = 12
    styleCenter.leading = 7
    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

    objs = []

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

    styleTCenter = deepcopy(styleT)
    styleTCenter.alignment = TA_CENTER

    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/>Код организации по ОКПО:<br/>'
                'Медицинская документация<br/>Учетная форма N 030/у</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']

    card_num_obj = patient_data['card_num'].split(' ')
    p_card_num = card_num_obj[0]
    if len(card_num_obj) == 2:
        p_card_type = '(' + str(card_num_obj[1]) + ')'
    else:
        p_card_type = ''

    diagnos = reg_dipensary.diagnos
    illnes = reg_dipensary.illnes
    doctor = reg_dipensary.doc_start_reg
    doc_speciality = "____________________"
    if doctor.specialities:
        doc_speciality = f"<u>{doctor.specialities.title}</u>"
    doc_fio = doctor.get_full_fio()
    date_start = reg_dipensary.date_start
    date_start = strdate(date_start, short_year=True)
    date_start = normalize_date(date_start)

    date_end = reg_dipensary.date_end
    if date_end:
        date_end = strdate(date_end, short_year=True)
        date_end = normalize_date(date_end)
    else:
        date_end = ""

    why_stop = reg_dipensary.why_stop

    if reg_dipensary.what_times == 1:
        what_times = "впервые - 1"
    elif reg_dipensary.what_times == 2:
        what_times = "повторно - 2"
    else:
        what_times = "впервые - 1, повторно - 2"

    if reg_dipensary.how_identified == 1:
        how_identified = "обращении за лечением - 1"
    elif reg_dipensary.how_identified == 2:
        how_identified = "профилактическом осмотре - 2"
    else:
        how_identified = "обращении за лечением - 1, профилактическом осмотре - 2"

    content_title = [
        Indenter(left=0 * mm),
        Spacer(1, 1 * mm),
        Paragraph('КОНТРОЛЬНАЯ КАРТА, ', styleCenter),
        Paragraph(
            'ДИСПАНСЕРНОГО НАБЛЮДЕНИЯ {}<font size=14>№</font><font fontname="PTAstraSerifBold" size=17> <u>{}</u></font><font size=14> {}</font>'
            .format(3 * space_symbol, p_card_num, p_card_type),
            styleCenter,
        ),
        Spacer(1, 7 * mm),
        Paragraph(
            f'1. Диагноз заболевания, по поводу которого пациент подлежит диспансерному наблюдению: <u>{illnes}</u> Код по МКБ-10: <u>{diagnos}</u>',
            style),
        Paragraph('2.Дата заполнения медицинской карты: _____________________',
                  style),
        Paragraph(
            f'3. Специальность врача: {doc_speciality} {4 * space_symbol} 4.ФИО врача: <u>{doc_fio}</u>',
            style),
        Paragraph(
            f'5. Дата установления диагноза: <u>{date_start}</u> {4 * space_symbol} 6. Диагноз установлен: {what_times}',
            style),
        Paragraph(f'7. Заболевание выявлено при: {how_identified}', style),
        Paragraph(
            f'8. Дата начала диспансерного наблюдения <u>{date_start}</u> {4 * space_symbol} 9. Дата прекращения диспансерного наблюдения {date_end}',
            style),
        Paragraph(
            f'10. Причины прекращения диспансерного наблюдения: <u>{why_stop}</u>',
            style),
        Paragraph(
            "11. Фамилия, имя, отчество:&nbsp;  <font size=11.7 fontname ='PTAstraSerifBold'> {} </font> "
            .format(patient_data['fio']), style),
        Paragraph(
            '12. Пол: {} {} 13. Дата рождения: {}'.format(
                patient_data['sex'], 3 * space_symbol, patient_data['born']),
            style),
        Paragraph(
            '14. Место регистрации: {}'.format(patient_data['main_address']),
            style),
        Paragraph('15. Код категории льготы:__________', style),
    ]

    objs.extend(content_title)
    objs.append(Spacer(1, 5 * mm))

    research_need = DispensaryPlan.objects.filter(diagnos=diagnos).order_by(
        'research__title', 'speciality__title')
    researches_list = []
    specialities_list = []
    visits_result = ""
    visits_plan = ""
    visits_research = VisitPurpose.objects.filter(
        title__icontains="диспансерн")

    current_year = datetime.datetime.now().year
    year = request_data.get('year', current_year)
    for i in research_need:
        if i.speciality:
            results = research_last_result_every_month(
                Researches.objects.filter(speciality=i.speciality), ind_card,
                year, visits_research)
            dates_result = ""
            dates_plan = ""
            plans = DispensaryRegPlans.objects.filter(
                card=ind_card,
                research=None,
                speciality=i.speciality,
                date__year=year).order_by('date')
            for p in plans:
                dates_plan = f"{dates_plan} {strfdatetime(p.date, '%d.%m')};"
            for r in range(12):
                if results[r]:
                    if r < 9:
                        dates_result = f"{dates_result} {results[r]['date']}.0{r + 1};"
                    else:
                        dates_result = f"{dates_result} {results[r]['date']}.{r + 1};"
            if i.is_visit:
                visits_result = dates_result
                visits_plan = dates_plan
            else:
                specialities_list.append(
                    f'{i.speciality.title}-{dates_plan}-{dates_result}')
        if i.research:
            dates_plan = " "
            plans = DispensaryRegPlans.objects.filter(
                card=ind_card,
                research=None,
                speciality=i.speciality,
                date__year=year).order_by('date')
            for p in plans:
                dates_plan = f"{dates_plan} {strfdatetime(p.date, '%d.%m')};"
            results = research_last_result_every_month([i.research], ind_card,
                                                       year)
            dates_result = ""
            for r in range(12):
                if results[r]:
                    if r < 9:
                        dates_result = f"{dates_result} {results[r]['date']}.0{r + 1};"
                    else:
                        dates_result = f"{dates_result} {results[r]['date']}.{r + 1};"
            researches_list.append(
                f'{i.research.title}-{dates_plan}-{dates_result}')

    researches_list.extend(specialities_list)
    visits_result = visits_result.split(';')[:-1]
    visits_plan = visits_plan.split(';')[:-1]
    visits_plan = [Paragraph(i, styleT) for i in visits_plan]
    if len(visits_plan) < 7:
        for i in range(7 - len(visits_plan)):
            visits_plan.append(Paragraph('', styleT))
    visits_plan.insert(0, Paragraph('Назначено явиться', styleT))

    visits_result = [Paragraph(i, styleT) for i in visits_result]
    if len(visits_result) < 7:
        for i in range(7 - len(visits_result)):
            visits_result.append(Paragraph('', styleT))
    visits_result.insert(0, Paragraph('Явился(лась)', styleT))

    opinion = [
        [
            Paragraph('Даты посещений', styleTCenter),
            Paragraph('', styleT),
            Paragraph('', styleT),
            Paragraph('', styleT),
            Paragraph('', styleT),
            Paragraph('', styleT),
            Paragraph('', styleT),
            Paragraph('', styleT),
        ],
        visits_plan,
        visits_result,
    ]

    tbl = Table(opinion,
                colWidths=(40 * mm, 20 * mm, 20 * mm, 20 * mm, 20 * mm,
                           20 * mm, 20 * mm, 20 * mm))
    tbl.setStyle(
        TableStyle([
            ('GRID', (0, 0), (-1, -1), 0.75, colors.black),
            ('SPAN', (0, 0), (-1, 0)),
        ]))
    objs.append(tbl)
    objs.append(PageBreak())
    objs.append(Paragraph('оборотная сторона ф. N 030/у', style))
    objs.append(Spacer(1, 5 * mm))

    visit_date = [Paragraph('', styleT) for i in range(7)]
    visit_date.insert(0, Paragraph('Даты посещений', styleTCenter))
    visits_plan = [Paragraph('', styleT) for i in range(7)]
    visits_plan.insert(0, Paragraph('Назначено явиться', styleT))
    visits_result = [Paragraph('', styleT) for i in range(7)]
    visits_result.insert(0, Paragraph('Явился(лась)я', styleT))

    opinion = [visit_date, visits_plan, visits_result]

    tbl = Table(opinion,
                colWidths=(40 * mm, 20 * mm, 20 * mm, 20 * mm, 20 * mm,
                           20 * mm, 20 * mm, 20 * mm))
    tbl.setStyle(
        TableStyle([
            ('GRID', (0, 0), (-1, -1), 0.75, colors.black),
            ('SPAN', (0, 0), (-1, 0)),
        ]))

    objs.append(tbl)
    objs.append(Spacer(1, 5 * mm))
    objs.append(Paragraph('17. Сведения об изменении диагноза', style))
    objs.append(Spacer(1, 2 * mm))
    empty_para = [Paragraph('', styleT) for i in range(4)]
    opinion = [
        [
            Paragraph('Дата', styleTCenter),
            Paragraph('Формулировка диагноза', styleT),
            Paragraph('Код по МКБ-10', styleT),
            Paragraph('ФИО врача', styleT),
        ],
        empty_para,
        empty_para,
    ]
    tbl = Table(opinion,
                colWidths=(30 * mm, 85 * mm, 30 * mm, 35 * mm),
                rowHeights=6 * mm)
    tbl.setStyle(TableStyle([
        ('GRID', (0, 0), (-1, -1), 0.75, colors.black),
    ]))
    objs.append(tbl)
    objs.append(Spacer(1, 3 * mm))
    objs.append(
        Paragraph(
            '18. Сопутствующие заболевания ______________________________________________________________________',
            style))
    objs.append(Spacer(1, 2 * mm))
    objs.append(
        Paragraph(
            '___________________________________________________________________________________________________',
            style))
    objs.append(Spacer(1, 1 * mm))
    objs.append(Paragraph('19. Лечебно-профилактические мероприятия', style))

    opinion_title = [
        Paragraph('N п/п', styleT),
        Paragraph('Мероприятия', styleT),
        Paragraph('Дата<br/> начала', styleT),
        Paragraph('Дата<br/>окончания', styleT),
        Paragraph('Отметка о<br/>выполнении', styleT),
        Paragraph('ФИО врача', styleT),
    ]

    opinion = [[
        '',
        Paragraph(f'{i.split("-")[0]}', styleT), '',
        Paragraph(f'{i.split("-")[2]}', styleT), ''
    ] for i in researches_list]
    opinion.insert(0, opinion_title)

    tbl = Table(opinion,
                colWidths=(10 * mm, 60 * mm, 25 * mm, 25 * mm, 23 * mm,
                           35 * mm))
    tbl.setStyle(TableStyle([
        ('GRID', (0, 0), (-1, -1), 0.75, colors.black),
    ]))
    objs.append(tbl)

    def first_pages(canvas, document):
        canvas.saveState()
        canvas.restoreState()

    def later_pages(canvas, document):
        canvas.saveState()
        canvas.restoreState()

    doc.build(objs, onFirstPage=first_pages, onLaterPages=later_pages)

    pdf = buffer.getvalue()
    buffer.close()

    return pdf