Exemplo n.º 1
0
def run(dictionnaire, template, dst):
    """Fonction qui prend en paramètre, le dictionnaire de contenu du fichier
    source, un template '.docx' où va être écrit le contenu du dictionnaire
    et un chemin de destination où sera enregistré le fichier final.
    """

    tpl = DocxTemplate(template)

    for fiche in dictionnaire['Fiches']:
        for key1, value1 in fiche.iteritems():
            if (isinstance(value1, basestring)
                    and ('Exigences' in key1 or 'Pre-requis' in key1)):

                value1 = value1.replace('\t', '')
                while value1.endswith('\n'):
                    value1 = value1[:-2]
                while value1.startswith('\n'):
                    value1 = value1[1:]
                fiche[key1] = RichText(value1)

            elif isinstance(value1, list):
                for elem in value1:
                    for key2, value2 in elem.iteritems():
                        elem[key2] = RichText(value2)

    context = dictionnaire

    tpl.render(context)
    tpl.save(dst)
Exemplo n.º 2
0
    def generate(self, rt_parent=None):
        context_table = {
            'headers': [],
            'data': [],
        }

        if self.headers:
            for header in self.headers:
                rt = RichText()
                for e in header:
                    rt.xml += e.generate().xml
                context_table['headers'].append(rt)

        for row in self.data:
            context_row = []
            for col in row:
                rt = RichText()
                for e in col:
                    rt.xml += e.generate().xml
                context_row.append(rt)
            context_table['data'].append(context_row)

        idTable = 'table_' + str(len(self.tables))
        xml = self.rawxml % (idTable + ".headers", idTable + ".data")
        self.tables[idTable] = context_table

        return {'table': context_table, 'xml': xml}
Exemplo n.º 3
0
	def generate(self,rt_parent = None):
		context_table = {
			'headers':[],
			'data':[],
		}
		
		if self.headers:
			for header in self.headers:
				rt = RichText()
				for e in header:
					rt.xml += e.generate().xml
				context_table['headers'].append(rt)

		for row in self.data:
			context_row = []
			for col in row:
				rt = RichText()
				for e in col:
					rt.xml += e.generate().xml
				context_row.append(rt)
			context_table['data'].append(context_row)

		xml = doJinjaRender(self.rawxml,context_table)
		
		return MDict({'table':context_table, 'xml':xml})
Exemplo n.º 4
0
Arquivo: text.py Projeto: noraj/MDdot
 def generate(self, rt=None):
     if not rt:
         rt = RichText()
     for i in range(len(self.text)):
         logger.spam("TextNode generation (text | option) : (%s | %s)" %
                     (repr(self.text[i]), self.options[i]))
         rt.add(self.text[i], **(self.options[i]))
     return rt
Exemplo n.º 5
0
    def get_sitem(self):
        tmp = self.to_dict(['ZHBH', 'XMMC', 'JG', 'YCTS', 'XMDW', 'CKFW'])
        if tmp['YCTS']:
            tmp['YCTS'] = RichText(tmp['YCTS'], color='FF0000', bold=True)
            tmp['JG'] = RichText(tmp['JG'], color='FF0000', bold=True)
        else:
            tmp['JG'] = RichText(tmp['JG'])

        return tmp
Exemplo n.º 6
0
def proc_dis(info):
    """处理其他变异信息中的遗传方式和表型
    """
    update_info = []
    for gene in info:
        dis_info = '\n'.join([xx['disease'] for xx in gene['diseases']])
        inheritance = '\n'.join(
            [xx['inheritance'] or '-' for xx in gene['diseases']])
        gene['dis_info'] = RichText(dis_info)
        gene['inheritance'] = RichText(inheritance)
        update_info.append(gene)
    return update_info
	def process_attachment_file(self, input_path, output_path, target=None):
		try:		
			output_path, _ = os.path.splitext(output_path)
			output_path += '.DOCX'		
			doc = DocxTemplate(input_path)
			rt = RichText()
			template_vars = mailer.render_DOC_template_var(self.application.config, target)
			rt.add('Alibaba',url_id=doc.build_url_id(template_vars['url']['webserver']))
			context = {'target_name': template_vars['client']['first_name'], 'target_email_address': template_vars['client']['email_address'], 'secret_id': template_vars['uid'], 'example': rt }	
			doc.render(context)
			doc.save(output_path)		
			return output_path
		except:
			return 0	
Exemplo n.º 8
0
 def _get_angles_list(self, without_h):
     angles_list = []
     newsymms = {}
     symms = {}
     num = 1
     for ang in self.cif.angles(without_h):
         symm1 = ang.symm1
         symm2 = ang.symm2
         if ang.symm1 == '.':
             symm1 = None
         if ang.symm2 == '.':
             symm2 = None
         num = symmsearch(self.cif, newsymms, num, symm1, symms)
         num = symmsearch(self.cif, newsymms, num, symm2, symms)
         symm1_str = '#' + str(symms[symm1]) if symm1 else ''
         symm2_str = '#' + str(symms[symm2]) if symm2 else ''
         angle_val = ang.angle_val.replace('-', minus_sign)
         # atom1 symm1_str a symm2_str
         atoms = RichText(ang.label1)
         atoms.add(symm1_str, superscript=True)
         a = '{}{}{}{}'.format(halbgeviert, ang.label2, halbgeviert, ang.label3)
         atoms.add(a, superscript=False)
         atoms.add(symm2_str, superscript=True)
         angles_list.append({'atoms': atoms, 'angle': angle_val})
         self.angles_as_string.append({'atom1': ang.label1,
                                       'atom2': a,
                                       'symm1': symm1_str,
                                       'symm2': symm2_str,
                                       'angle': angle_val})
     self._symmlist.update(newsymms)
     return angles_list
Exemplo n.º 9
0
def docx_export(issues):
    tpl = DocxTemplate('issues_tpl.docx')
    issueEmpty = GitIssue('', '', '', '')

    context = {'issues': []}

    for i in range(0, len(issues), 3):
        issue1 = issues[i]
        issue2 = issueEmpty
        issue3 = issueEmpty
        if i + 1 < len(issues):
            issue2 = issues[i + 1]
        if i + 2 < len(issues):
            issue3 = issues[i + 2]

        item = {
            'n1':
            issue1.n,
            'title1':
            to_fix_size(issue1.title, 29),
            'body1':
            RichText(to_fix_size(issue1.body, 200), size=14),
            'image1':
            InlineImage(tpl, issue1.image, height=Inches(0.64))
            if issue1.image else '',
            'n2':
            issue2.n,
            'title2':
            to_fix_size(issue2.title, 29),
            'body2':
            RichText(to_fix_size(issue2.body, 200), size=14),
            'image2':
            InlineImage(tpl, issue2.image, height=Inches(0.64))
            if issue2.image else '',
            'n3':
            issue3.n,
            'title3':
            to_fix_size(issue3.title, 29),
            'body3':
            RichText(to_fix_size(issue3.body, 200), size=14),
            'image3':
            InlineImage(tpl, issue3.image, height=Inches(0.64))
            if issue3.image else '',
        }
        context['issues'].append(item)

    # testing that it works also when autoescape has been forced to True
    jinja_env = jinja2.Environment(autoescape=True)
    tpl.render(context, jinja_env)
    tpl.save('inline_image.docx')
Exemplo n.º 10
0
    def __get_row_structure(df, cell_format_config, row_group=None):
        row_list = []
        row_id = 0
        for cur_row_data in df.index:
            row_id = row_id + 1
            col_dict = GridBuilder.__get_column_structure_by_section(
                GridBuilder.__get_df_row_segment(df, cur_row_data),
                cell_format_config, row_id, row_group)
            col_dict['label'] = RichText(
                cur_row_data,
                bold=cell_format_config[CELL_FORMAT_DEFAULT_KEY].get(
                    'make_labels_bold', False),
                size=cell_format_config[CELL_FORMAT_DEFAULT_KEY].get(
                    'row_label_font_size', 8))
            # if background colour is specified:
            if (CELL_FORMAT_DEFAULT_KEY in cell_format_config) & (
                    'background_colour_ftn'
                    in cell_format_config[CELL_FORMAT_DEFAULT_KEY]):
                background_colour = cell_format_config[
                    CELL_FORMAT_DEFAULT_KEY]['background_colour_ftn'](None,
                                                                      None,
                                                                      None,
                                                                      None,
                                                                      row_id)
                col_dict['bg'] = background_colour

            row_list.append(col_dict)

        return row_list
Exemplo n.º 11
0
def save_document_view(request):
    """
    Save file (preavis)
    """
    settings = request.registry.settings
    mails_templates_directory = settings['mails_templates_directory']
    affaires_directory = settings['affaires_directory']

    # Get request params
    affaire_id = str(request.params['affaire_id'])
    template = request.params['template']
    values = request.params['values']
    service_id = request.params[
        'service_id'] if 'service_id' in request.params else None
    relPath = request.params['relpath'].strip('/').strip(
        '\\') if 'relpath' in request.params else ""
    filename = request.params[
        'filename'] if 'filename' in request.params else None

    # Set output file name
    output_file_name = filename if filename is not None else template
    if service_id:
        service = request.dbsession.query(Service).filter(
            Service.id == service_id).first()
        output_file_name += "_" + service.abreviation
        relPath = service.relpath.strip('/').strip('\\')

    affaire_relpath = request.dbsession.query(Affaire).filter(
        Affaire.id == affaire_id).first().chemin

    if affaire_relpath is None:
        affaire_relpath = affaire_id

    affaire_path = os.path.normcase(
        os.path.join(affaires_directory, affaire_relpath))

    filename = output_file_name + '.docx'
    file_path = os.path.normcase(os.path.join(affaire_path, relPath, filename))

    if not os.path.exists(affaire_path):
        Utils.create_affaire_folder(request, affaire_path)
        # update affaire chemin
        affaire = request.dbsession.query(Affaire).filter(
            Affaire.id == affaire_id).first()
        affaire.chemin = affaire_relpath

    # Set context
    context = json.loads(values)
    for key in context.keys():
        context[key] = RichText(context[key])

    # Ouverture du document template
    doc = DocxTemplate(
        os.path.join(mails_templates_directory, template + ".docx"))

    # Replace values by keywords and save
    doc.render(context)
    doc.save(file_path)

    return {'filename': filename, "folderpath": relPath}
Exemplo n.º 12
0
def generate_questionnaire_file(questionnaire):
    """
    Generate a word Docx document for the given questionnaire.
    The generated docment is based on a Docx template.
    This is made possible thanks to docxtepl Python package.
    """
    doc = DocxTemplate(settings.TEMPLATE_DIR + "/ecc/questionnaire.docx")
    context = {
        'questionnaire': questionnaire,
        'description': RichText(questionnaire.description)
    }
    # Note : autoescape is for HTML-escaping the user-provided questionnaire data, for XSS
    # protection.
    doc.render(context, autoescape=True)
    filename = f'Questionnaire-{questionnaire.numbering}.docx'
    # Why do we need both relative and absolte path?
    # For django's FileField, we need a relative path from the root of the MEDIA_ROOT.
    # For saving the file via DocxTemplate, we need to absolute path.
    relative_path = questionnaire_file_path(questionnaire, filename)
    absolute_path = os.path.join(settings.MEDIA_ROOT, relative_path)
    file_folder = ntpath.split(absolute_path)[0]
    if not os.path.exists(file_folder):
        os.makedirs(file_folder)
    doc.save(absolute_path)
    questionnaire.generated_file = relative_path
    questionnaire.save()
Exemplo n.º 13
0
    def write_rich(self, text_variable, text_content, render_italic=False,
                   render_underlined=False, render_bold=False, render_color='#000000',
                   render_size=24, render_strike=False, render_font='Times New Roman'):
        """
            Rich text render
            :param render_font:
            :param text_variable:
            :param text_content
            :param render_underlined:
            :param render_bold: False
            :param render_italic: False
            :param render_strike: False
            :param render_color: '#000000'
            :param render_size: 14
            :return: self
        """

        rich_text = RichText(text_content, italic=render_italic,
                             bold=render_bold, strike=render_strike,
                             color=render_color, size=render_size, font=render_font, underline=render_underlined)

        context = {text_variable: rich_text}

        self.document = DocxTemplate(self.path_to_sample)
        self.document = DocxTemplate(self.path_to_sample)
        self.document.render(context)
Exemplo n.º 14
0
def markdown_to_docx(text, tpl):
    if get_config('new markdown to docx', False):
        source_code = docassemble.base.filter.markdown_to_html(text,
                                                               do_terms=False)
        source_code = re.sub("\n", ' ', source_code)
        source_code = re.sub(">\s+<", '><', source_code)
        soup = BeautifulSoup('<html>' + source_code + '</html>', 'html.parser')
        parser = SoupParser(tpl)
        for elem in soup.find_all(recursive=False):
            parser.traverse(elem)
        output = text_type(parser)
        # logmessage(output)
        return output
    else:
        source_code = docassemble.base.filter.markdown_to_html(text,
                                                               do_terms=False)
        source_code = re.sub(r'(?<!\>)\n', ' ', source_code)
        #source_code = re.sub("\n", ' ', source_code)
        #source_code = re.sub(">\s+<", '><', source_code)
        rt = RichText('')
        soup = BeautifulSoup(source_code, 'lxml')
        html_parsed = deque()
        html_parsed = html_linear_parse(soup)
        rt = add_to_rt(tpl, rt, html_parsed)
        return rt
Exemplo n.º 15
0
def download(file_type):
    '''下载接口'''

    if file_type not in ['form','scheme']:abort(404)
    id = request.form.get('id')
    type = request.form.get('type')
    data = query_data(type,id)
    #下载策划
    if file_type == 'scheme':
        if data.filename == 'Nothing':abort(404)
        content = send_file(path.join(Upload_path,data.rand_filename))
        filename = quote(data.filename)
    #if data.applicant!=current_user.name :abort(404)
    else :
        #生成context并进行渲染
        context=make_context(data,type)
        for key,value in context.items() :
            context[key] = RichText(value)     
        doc = DocxTemplate(path.join(Docx_path,type+'.docx'))
        doc.render(context)
        temp_file = path.join(Upload_path,str(current_user.id) +'result.docx')
        doc.save(temp_file)
        #读取渲染后的文件并将之删除
        with open(temp_file,'rb') as f:
            content = f.read()
        if path.exists(temp_file):
            remove(temp_file)
        filename = quote(data.association+'-'+types[type][1]+'.docx')     
 
    response = make_response(content)
    response.headers['Content-Disposition'] = \
    "attachment;filename*=UTF-8''" + filename
    response.headers['Content-Type'] = 'application/octet-stream'
    return response
Exemplo n.º 16
0
def courrier_affaire_view(request):
    """
    Create  file
    """
    settings = request.registry.settings
    mails_templates_directory = settings['mails_templates_directory']
    temporary_directory = settings['temporary_directory']

    # Get request params
    template = request.params['template']
    values = request.params['values']
    output_file_name = request.params['output_file_name'] if 'output_file_name' in request.params else template

    # Set output file name
    date_time = datetime.now().strftime("%Y%m%d")
    filename = output_file_name + "_" + date_time + '.docx'
    file_path = os.path.join(temporary_directory, filename)

    # Set context
    context = json.loads(values)
    for key in context.keys():
        context[key] = RichText(context[key])

    # Ouverture du document template
    doc = DocxTemplate(os.path.join(mails_templates_directory, template + ".docx"))

    # Replace values by keywords and save
    doc.render(context)
    doc.save(file_path)

    return {'filename': filename}
Exemplo n.º 17
0
def get_scores_for_para(scores):
    scores_for_para = {}

    for (key, value) in scores.items():
        if value[0] >= 60:
            color = NORMAL_COLOR
        else:
            color = ABNORMAL_COLOR

        value_tmp = [
            RichText(" {} ".format(value[0]), color=color, underline=True),
            RichText(" {} ".format(value[2]), color=color, underline=True)
        ]

        scores_for_para[key] = value_tmp

    return scores_for_para
Exemplo n.º 18
0
 def _get_bonds_list(self, without_h):
     bonds = []
     num = 1
     newsymms = {}
     symms = {}
     for at1, at2, dist, symm2 in self.cif.bonds(without_h):
         dist = dist.replace('-', minus_sign)
         if symm2 == '.':
             symm2 = None
         num = symmsearch(self.cif, newsymms, num, symm2, symms)
         # Atom1 - Atom2:
         a = '{}{}{}'.format(at1, halbgeviert, at2)
         symm = '#' + str(symms[symm2]) if symm2 else ''
         atoms = RichText(a)
         atoms.add(symm, superscript=True)
         bonds.append({'atoms': atoms, 'dist': dist})
         self.bonds_as_string.append({'atoms': a, 'symm': symm, 'dist': dist})
     self._symmlist.update(newsymms)
     return bonds
Exemplo n.º 19
0
 def __get_rich_text_columns(col_list, cell_format_config):
     ret_list = []
     for cur_col in col_list:
         cur_col = str(cur_col)
         ret_list.append(
             RichText(cur_col,
                      bold=True,
                      size=cell_format_config[CELL_FORMAT_DEFAULT_KEY]
                      ['col_label_font_size']))
     return ret_list
Exemplo n.º 20
0
def pdf_profil_student(data):
    connect_to_bdd = sqlite3.connect('donnee.db')
    cur = connect_to_bdd.cursor()
    get_profil_student = cur.execute(
        ''' 
	SELECT matricule_etud, nom, prenom, date_naissance, tel, email, cin, adresse, niveau, pdp_name FROM ETUDIANT
	WHERE matricule_etud=?
	''', (data, ))
    resu = get_profil_student.fetchall()
    info = {
        'num_matricule': RichText(resu[0][0],
                                  font='Arial',
                                  bold=False,
                                  size=24),
        'nom': RichText(resu[0][1], font='Arial', bold=False, size=24),
        'prenom': RichText(resu[0][2], font='Arial', bold=False, size=24),
        'date_naissance': RichText(resu[0][3],
                                   font='Arial',
                                   bold=False,
                                   size=24),
        'tel': RichText(resu[0][4], font='Arial', bold=False, size=24),
        'email': RichText(resu[0][5], font='Arial', bold=False, size=24),
        'cin': RichText(resu[0][6], font='Arial', bold=False, size=24),
        'adresse': RichText(resu[0][7], font='Arial', bold=False, size=24),
        'niveau': RichText(resu[0][8], font='Arial', bold=False, size=24)
    }

    #get tamplate
    document = DocxTemplate(f"template/template_etudiant.docx")

    #change image in the template
    if resu[0][9] != '':
        document.replace_pic(
            'face0.png',
            os.getcwd() + f"\\src\\dist\\img\\pdp\\{resu[0][9]}")

    #creation template
    document.render(info)
    name = "Profil_" + resu[0][1] + "_" + resu[0][2]

    #save doc created
    document.save(f"{gettempdir()}\\{name}.docx")

    #convertion template to pdf
    dirpath = os.environ.get('USERPROFILE') + "\\Desktop"
    pdf_got = f"{dirpath}\\{name}.pdf"
    convert(f"{gettempdir()}\\{name}.docx", pdf_got)
    return pdf_got
Exemplo n.º 21
0
 def _get_hydrogen_bonds(self) -> List[dict]:
     symms = {}
     newsymms = {}
     num = 1
     atoms_list = []
     for h in self.cif.hydrogen_bonds():
         symm = h.symm
         if symm == '.':
             symm = None
         num = symmsearch(self.cif, newsymms, num, symm, symms)
         symmval = ('#' + str(symms[symm])) if symm else ''
         a = h.label_d + halbgeviert + h.label_h + ellipsis_mid + h.label_a
         atoms = RichText(a)
         atoms.add(symmval, superscript=True)
         atoms_list.append({'atoms'  : atoms, 'dist_dh': h.dist_dh, 'dist_ha': h.dist_ha,
                            'dist_da': h.dist_da, 'angle_dha': h.angle_dha})
         self.hydrogen_bonds_as_str.append({'atoms'  : a, 'dist_dh': h.dist_dh, 'dist_ha': h.dist_ha,
                                            'dist_da': h.dist_da, 'angle_dha': h.angle_dha, 'symm': symmval})
     self._symmlist = newsymms
     return atoms_list
Exemplo n.º 22
0
def markdown_to_docx(text, tpl):
    source_code = docassemble.base.filter.markdown_to_html(text, do_terms=False)
    source_code = re.sub(r'(?<!\>)\n', ' ', source_code)
    #source_code = re.sub("\n", ' ', source_code)
    #source_code = re.sub(">\s+<", '><', source_code)
    rt = RichText('')
    soup = BeautifulSoup(source_code, 'lxml')
    html_parsed = deque()
    html_parsed = html_linear_parse(soup)
    rt = add_to_rt(tpl, rt, html_parsed)
    return rt
Exemplo n.º 23
0
 def __unicode__(self):
     output = ''
     list_number = 1
     for para in self.paragraphs:
         logmessage("Got a paragraph where style is " + para['params']['style'] + " and indentation is " + text_type(para['params']['indentation']))
         output += '<w:p><w:pPr><w:pStyle w:val="Normal"/>'
         if para['params']['style'] in ('ul', 'ol', 'blockquote'):
             output += '<w:ind w:left="' + text_type(36*para['params']['indentation']) + '" w:right="0" w:hanging="0"/>'
         output += '<w:rPr></w:rPr></w:pPr>'
         if para['params']['style'] == 'ul':
             output += text_type(RichText("•\t"))
         if para['params']['style'] == 'ol':
             output += text_type(RichText(text_type(list_number) + ".\t"))
             list_number += 1
         else:
             list_number = 1
         for run in para['runs']:
             output += text_type(run)
         output += '</w:p>'
     return output
Exemplo n.º 24
0
Arquivo: text.py Projeto: noraj/MDdot
    def _setImage(self, block):
        # If all is ok, image otken must be alone in paragraph token
        captionxml = """</w:p><w:p><w:pPr><w:pStyle w:val="%s"/></w:pPr>"""

        idImage = 'image_' + str(len(self.images))

        text = "{{ %s.image }}" % (idImage)
        self._addText(text, {})
        if block.title:
            rt = RichText()
            rt.xml = captionxml % (self.styles[self.CAPTION],
                                   escape(block.title))
            self._addText(rt, {})
        elif block.children:
            rt = RichText()
            rt.xml = captionxml % (self.styles[self.CAPTION])
            self._addText(rt, {})
            self._parseChild(block, {'style': self.styles[self.CAPTION]})

        src = os.path.join(self.ressourcePath, block.src)
        self.images[idImage] = {
            'src': src,
            'title': block.title,
            'id': self.id
        }
Exemplo n.º 25
0
 def __str__(self):
     output = ''
     for para in self.paragraphs:
         # logmessage("Got a paragraph where style is " + para['params']['style'] + " and indentation is " + str(para['params']['indentation']))
         output += '<w:p><w:pPr><w:pStyle w:val="Normal"/>'
         if para['params']['style'] in (
                 'ul',
                 'blockquote') or para['params']['style'].startswith('ol'):
             output += '<w:ind w:left="' + str(
                 36 * para['params']['indentation']
             ) + '" w:right="0" w:hanging="0"/>'
         output += '<w:rPr></w:rPr></w:pPr>'
         if para['params']['style'] == 'ul':
             output += str(RichText("•\t"))
         if para['params']['style'] == 'ol1':
             output += str(
                 RichText(str(para['params']['list_number']) + ".\t"))
         elif para['params']['style'] == 'olA':
             output += str(
                 RichText(Alpha(para['params']['list_number']) + ".\t"))
         elif para['params']['style'] == 'ola':
             output += str(
                 RichText(alpha(para['params']['list_number']) + ".\t"))
         elif para['params']['style'] == 'olI':
             output += str(
                 RichText(
                     Roman_Numeral(para['params']['list_number']) + ".\t"))
         elif para['params']['style'] == 'oli':
             output += str(
                 RichText(
                     roman_numeral(para['params']['list_number']) + ".\t"))
         for run in para['runs']:
             output += str(run)
         output += '</w:p>'
     return output
Exemplo n.º 26
0
def row_1(rule, obj):
	cells = obj.find_all('td')
	no = cells[0].get_text()
	if (rule['no'] != no):
		rule['no'] = RichText(rule['no'])
		rule['no'].add('\n')
		rule['no'].add(no, style='Style2')
	else:
		rule['no'] = RichText(rule['no'])

	for el in cells[3].find_all('font', {'style': "BACKGROUND-COLOR: pink"}):
		rule['name'].add(el.get_text(), style='Style2')
		rule['name'].add('\n')

	for el in cells[4].find_all('font', {'style': "BACKGROUND-COLOR: pink"}):
		rule['source'].add(el.get_text(), style='Style2')
		rule['source'].add('\n')

	for el in cells[5].find_all('font', {'style': "BACKGROUND-COLOR: pink"}):
		rule['dest'].add(el.get_text(), style='Style2')
		rule['dest'].add('\n')

	for el in cells[6].find_all('font', {'style': "BACKGROUND-COLOR: pink"}):
		rule['ser'].add(el.get_text(), style='Style2')
		rule['ser'].add('\n')

	for el in cells[7].find_all('font', {'style': "BACKGROUND-COLOR: pink"}):
		rule['act'].add(el.get_text(), style='Style2')
		rule['act'].add('\n')

	for el in cells[10].find_all('font', {'style': "BACKGROUND-COLOR: pink"}):
		rule['enable'].add(el.get_text(), style='Style2')
		rule['enable'].add('\n')

	for el in cells[12].find_all('font', {'style': "BACKGROUND-COLOR: pink"}):
		rule['exp'].add(el.get_text(), style='Style2')
		rule['exp'].add('\n')

	return rule
Exemplo n.º 27
0
 def __init__(self, tpl):
     self.paragraphs = [dict(params=dict(style='p', indentation=0), runs=[RichText('')])]
     self.current_paragraph = self.paragraphs[-1]
     self.run = self.current_paragraph['runs'][-1]
     self.bold = False
     self.italic = False
     self.underline = False
     self.strike = False
     self.indentation = 0
     self.style = 'p'
     self.still_new = True
     self.size = None
     self.tpl = tpl
Exemplo n.º 28
0
 def new_paragraph(self):
     if self.still_new:
         # logmessage("new_paragraph is still new and style is " + self.style + " and indentation is " + text_type(self.indentation))
         self.current_paragraph['params']['style'] = self.style
         self.current_paragraph['params']['indentation'] = self.indentation
         return
     # logmessage("new_paragraph where style is " + self.style + " and indentation is " + text_type(self.indentation))
     self.current_paragraph = dict(params=dict(
         style=self.style, indentation=self.indentation),
                                   runs=[RichText('')])
     self.paragraphs.append(self.current_paragraph)
     self.run = self.current_paragraph['runs'][-1]
     self.still_new = True
Exemplo n.º 29
0
 def __init__(self, tpl):
     self.runs = [RichText('')]
     self.run = self.runs[-1]
     self.bold = False
     self.italic = False
     self.underline = False
     self.indentation = 0
     self.style = 'p'
     self.strike = False
     self.size = None
     self.tpl = tpl
     self.at_start = True
     self.list_number = 1
Exemplo n.º 30
0
 def format_sum_formula(self, sum_formula: str) -> RichText:
     sum_formula_group = [''.join(x[1]) for x in itertools.groupby(sum_formula, lambda x: x.isalpha())]
     richtext = RichText('')
     if sum_formula_group:
         for _, word in enumerate(sum_formula_group):
             if isnumeric(word):
                 richtext.add(word, subscript=True)
             else:
                 richtext.add(word)
         return richtext
     else:
         return RichText('No sum formula')
Exemplo n.º 31
0
# -*- coding: utf-8 -*-
'''
Created : 2015-03-26

@author: Eric Lapouyade
'''

from docxtpl import DocxTemplate, RichText

tpl=DocxTemplate('test_files/richtext_tpl.docx')

rt = RichText('an exemple of ')
rt.add('a rich text', style='myrichtextstyle')
rt.add(' with ')
rt.add('some italic', italic=True)
rt.add(' and ')
rt.add('some violet', color='#ff00ff')
rt.add(' and ')
rt.add('some striked', strike=True)
rt.add(' and ')
rt.add('some small', size=14)
rt.add(' or ')
rt.add('big', size=60)
rt.add(' text.')
rt.add(' Et voilà ! ')
rt.add('\n1st line')
rt.add('\n2nd line')
rt.add('\n3rd line')
rt.add('\n\n<cool>')

context = {