Exemplo n.º 1
0
def transform_for_docx(text, question, tpl, width=None):
    if type(text) in (int, float, bool, NoneType):
        return text
    text = unicode(text)
    m = re.search(r'\[FILE ([^,\]]+), *([0-9\.]) *([A-Za-z]+) *\]', text)
    if m:
        amount = m.group(2)
        units = m.group(3).lower()
        if units in ['in', 'inches', 'inch']:
            the_width = Inches(amount)
        elif units in ['pt', 'pts', 'point', 'points']:
            the_width = Pt(amount)
        elif units in ['mm', 'millimeter', 'millimeters']:
            the_width = Mm(amount)
        else:
            the_width = Pt(amount)
        file_info = server.file_finder(m.group(1),
                                       convert={'svg': 'png'},
                                       question=question)
        if 'fullpath' not in file_info:
            return '[FILE NOT FOUND]'
        return InlineImage(tpl, file_info['fullpath'], the_width)
    m = re.search(r'\[FILE ([^,\]]+)\]', text)
    if m:
        file_info = server.file_finder(m.group(1),
                                       convert={'svg': 'png'},
                                       question=question)
        if 'fullpath' not in file_info:
            return '[FILE NOT FOUND]'
        return InlineImage(tpl, file_info['fullpath'], Inches(2))
    return docassemble.base.filter.docx_template_filter(text)
Exemplo n.º 2
0
    def generate_img_doc(self):  # 生成证据单的函数,用docxtpl模块,以tpl指定的文件为模板进行元素替换。
        index = 0  # 图片编号
        for file in os.listdir(self.original_current_path):  # 历遍图片文件
            if 'jpg' in file.lower() or 'jpeg' in file.lower():  # 判断文件名是否图片
                index = index + 1  # 找到后,序号加1
                try:
                    tpl = DocxTemplate(self.img_tpl_path)  # 指定的模板
                    image = self.original_current_path + file
                    img_doc_path = self.target_current_path + '\\' + self.corp_name + '-照片-' + str(
                        index) + '.docx'  # 路径(全局变量)+字号+序号+格式

                    img = Image.open(image)
                    if img.size[0] > img.size[1]:
                        self.attributes_values['image'] = InlineImage(
                            tpl, image, width=Mm(153))  # 替换图片
                    else:
                        self.attributes_values['image'] = InlineImage(
                            tpl, image, width=Mm(130))  # 替换图片

                    try:
                        tpl.render(self.attributes_values)  # 执行替换
                        tpl.save(img_doc_path)  # 保存文件
                    except UnrecognizedImageError:
                        content = file + '不是有效的图片文件,无法生成证据提取单'
                        post_progress(content)
                except Exception:
                    self.failed_dirs.append('处理' + file + '的图片时出错')
            else:
                pass
Exemplo n.º 3
0
    def generate_department_docx_report(self, _data, _doc_id, filename):
        if _data is None:
            return None
        else:
            # Generate the histogram file
            temp1 = tempfile.NamedTemporaryFile(
                prefix="measurement_histogram_", suffix=".png")
            temp2 = tempfile.NamedTemporaryFile(
                prefix="measurement_histogram_", suffix=".png")

            self.generate_low_high_images(_data, temp1, temp2)

            tpl = DocxTemplate(_template_department_report)

            context = {
                'low_image':
                InlineImage(tpl, temp1, width=Inches(3), height=Inches(3)),
                'high_image':
                InlineImage(tpl, temp2, width=Inches(3), height=Inches(3)),
                'time':
                datetime.datetime.now().strftime("%y-%m-%d, %H:%M:%S"),
                'id':
                str(_doc_id),
            }
            context = {**_data, **context}
            tpl.render(context)
            tpl.save(filename)
            temp1.close()
            temp2.close()
        return filename
Exemplo n.º 4
0
def setpictosrc(path,check_app,tpl,filelists,file_path,use_tab = ''):
    context_pic = {}
    if filelists:
        for file_count,file_name in enumerate(filelists):
            file_path_output = path+'/Report'+file_path+'/pic/'+filelists[file_count]
            # context_pic_key = 'productPic'+str(file_count)
            if(use_tab == ''):
                if(file_count == 0):
                    context_pic_key = 'fornt_side'
                elif(file_count == 1):
                    context_pic_key = 'back_side'
                elif(file_count == 2):
                    context_pic_key = 'label'
                else:
                    context_pic_key = 'null'+str(file_count)
            else:
                context_pic_key = use_tab+str(file_count)

            if(check_app == ''):
                context_pic_value = InlineImage(tpl,file_path_output, width=Mm(60))
            else:
                context_pic_value = InlineImage(tpl,file_path_output, width=Mm(40))
                if(file_count == 2):
                    context_pic_value = InlineImage(tpl,file_path_output, width=Mm(80))
            context_pic.update({context_pic_key:context_pic_value})
    return(context_pic)
Exemplo n.º 5
0
def get_inline_image(doc, path, width=None, height=None):
    if width is not None and height is not None:
        return InlineImage(doc, path, width=Mm(int(width)), height=Mm(int(height)))
    if width:
        return InlineImage(doc, path, width=Mm(int(width)))
    if height:
        return InlineImage(doc, path, height=Mm(int(height))),
    else:
        return InlineImage(doc, path),
Exemplo n.º 6
0
    def get_FDR_mapping(self, report_path, HL_flag):
        if HL_flag == 'H':
            img = Image.open(path.join(report_path, 'hcoverage.png'))
        else:
            img = Image.open(path.join(report_path, 'lcoverage.png'))
        img = img.crop((60, 0, 1170, img.size[-1]))
        pix = img.load()
        color_cells_location = []
        for x in range(img.size[0]):
            for y in range(img.size[-1]):
                if pix[x, y] == (255, 0, 0):
                    color_cells_location.append(y)
        start_anchor = self.get_FDR_anchor(color_cells_location)
        end_anchor = start_anchor[1:] + [img.size[-1] + 26]

        for i in range(len(start_anchor)):
            if start_anchor[i] + 603 < end_anchor[i]:
                if HL_flag == 'H':
                    img.crop((0, start_anchor[i] - 26, img.size[0],
                              start_anchor[i] + 603)).save(
                                  path.join('temp',
                                            '{}{}.png'.format('hfdr', i)))
                elif HL_flag == 'L':
                    img.crop((0, start_anchor[i] - 26, img.size[0],
                              start_anchor[i] + 603)).save(
                                  path.join('temp',
                                            '{}{}.png'.format('lfdr', i)))
            else:
                if HL_flag == 'H':
                    img.crop((0, start_anchor[i] - 26, img.size[0],
                              end_anchor[i] - 26)).save(
                                  path.join('temp',
                                            '{}{}.png'.format('hfdr', i)))
                elif HL_flag == 'L':
                    img.crop((0, start_anchor[i] - 26, img.size[0],
                              end_anchor[i] - 26)).save(
                                  path.join('temp',
                                            '{}{}.png'.format('lfdr', i)))

        if HL_flag == 'H':
            FDR_mapping_format = [{
                'img':
                InlineImage(self.tpl, img_name, width=Mm(165))
            } for img_name in sorted(glob(path.join('temp', 'hfdr*')))]
        else:
            FDR_mapping_format = [{
                'img':
                InlineImage(self.tpl, img_name, width=Mm(165))
            } for img_name in sorted(glob(path.join('temp', 'lfdr*')))]

        return FDR_mapping_format
Exemplo n.º 7
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.º 8
0
    def __insert_image(self):
        if 'HRD_rank_plot' in self.patientDict:
            HRD_rank_plot = self.patientDict['HRD_rank_plot']
            self.dict2['HRD_rank_plot'] = InlineImage(self.doc,
                                                      HRD_rank_plot,
                                                      width=Mm(100))

        if 'figurePath' in self.patientDict['TMB']:
            figurePath = self.patientDict['TMB']['figurePath']
            self.dict2['TMB']['figurePath'] = InlineImage(self.doc,
                                                          figurePath,
                                                          width=Mm(100))
        # self.doc.render(self.patientDict, autoescape=True)
        self.__rich()
        self.doc.render(self.dict2, autoescape=True)
Exemplo n.º 9
0
    def _put_images_into_context(self, template, context):

        image_initial = App.get_running_app().config.get(
            "templates", "image_initial")
        for k in list(context.keys()):
            if k.startswith(image_initial):
                image_attribs = dict([[
                    j.strip().strip("\"\'").strip()
                    for j in i.strip().split("=")
                ] for i in context[k].split(",")])
                image_attribs = {
                    "image_descriptor":
                    image_attribs.get("path", None),
                    "width":
                    int(image_attribs.get("width", None)) if image_attribs.get(
                        "width", None) else None,
                    "height":
                    int(image_attribs.get("height", None))
                    if image_attribs.get("height", None) else None,
                }

                if "image_descriptor" in image_attribs and os.path.exists(
                        image_attribs["image_descriptor"]):
                    context[k] = InlineImage(template, **image_attribs)
                else:
                    context.pop(k)
        return context
Exemplo n.º 10
0
def CreateReporter(request):
    # os.path.dirname(path) : It is used to return the directory name from the path given.
    # This function returns the name from the path except the path name.

    # os.path.abspath(path) returns the pathname to the path passed as a parameter to this function

    BASE_DIR = os.path.dirname(__file__)
    doc = DocxTemplate(
        os.path.join(BASE_DIR,
                     "templates/docxtpl_Reporter/my_word_template.docx"))
    foto = InlineImage(doc, 'media/Firma.png', width=Pt(100))
    context = {'company_name': "World company", 'foto': foto}

    doc_io = io.BytesIO(
    )  # create a file-like object. Call io module and instance BytesIO class
    # Data can be kept as bytes in an in-memory buffer

    doc.render(context)  # render document using dict context
    doc.save(doc_io)  # save data to file-like object
    doc_io.seek(0)  # go to the beginning of the file-like object
    response = HttpResponse(doc_io.read())

    # Content-Disposition header makes a file downloadable
    response["Content-Disposition"] = "attachment; filename=" + context[
        'company_name'] + ".docx"

    # Set the appropriate Content-Type for docx file
    response[
        "Content-Type"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"

    # Now, it is always a good practice to close our buffer handle whenever we have done our work.
    # This is also to make sure that we free whatever memory we’ve allocated for the buffer.
    doc_io.close()
    return response
Exemplo n.º 11
0
    def toInlineImg(key):
        tmp_img_file = tempfile.NamedTemporaryFile(delete=None, suffix='.jpg')
        tmp_img_file.write(base64.urlsafe_b64decode(context[key]))
        tmp_img_file.close()

        context[key] = InlineImage(doc, tmp_img_file.name)
        return tmp_img_file.name
Exemplo n.º 12
0
def generate_game_roadmaps(target_file):
    files_to_merge = list()
    with tempfile.TemporaryDirectory() as tmpdir:
        for game in Game.objects():
            tpl = DocxTemplate(GAME_ROADMAP_TEMPLATE)

            qr = pyqrcode.create(game.hash, error=QR_ERROR, version=QR_VERSION)
            qr_file = os.path.join(tmpdir, "game.png")
            qr.png(qr_file,
                   scale=QR_SCALE,
                   module_color=QR_COLOR,
                   quiet_zone=QUIET_ZONE)

            context = dict(gameName=game.name,
                           gId=str(game.number),
                           circuit=game.circuit,
                           leader=game.leader,
                           qrCode=InlineImage(tpl, qr_file, width=Mm(QR_SIZE)))

            for i, match in enumerate(game.matches, 1):
                context["players{}".format(i)] = "{} - {}".format(
                    match.players_code[0], match.players_code[1])

            tpl.render(context)
            game_file = os.path.join(tmpdir, "game{}.docx".format(game.number))
            tpl.save(game_file)
            files_to_merge.append(game_file)

        _combine_docx(target_file, files_to_merge)
Exemplo n.º 13
0
def read_excel():
    # 打开文件
    workbook = xlrd.open_workbook(r'C:\autoreport\风资源工作簿-zyc修改.xlsm')
    tpl = DocxTemplate(r'C:\autoreport\华润template.docx')
    images = r'C:\autoreport\12345.png'
    # 获取所有sheet
    print(workbook.sheet_names())
    sheet2_name = workbook.sheet_names()[1]

    # 根据sheet索引或者名称获取sheet内容
    # sheet2 = workbook.sheet_by_index(1)  # sheet索引从0开始
    sheet2 = workbook.sheet_by_name('风电场概况')
    number_of_tower = sheet2.cell(15, 5)
    # sheet的名称,行数,列数
    print(sheet2.name, sheet2.nrows, sheet2.ncols)

    context = {'number_of_tower': InlineImage(tpl, images, width=Mm(20))}
    tpl.render(context)
    tpl.save(r'C:\autoreport\result.docx')

    # 获取整行和整列的值(数组)
    # rows = sheet2.row_values(15)  # 获取第四行内容
    # cols = sheet2.col_values(3)  # 获取第三列内容
    # print(rows)
    # print(cols)

    # 获取单元格内容
    print(sheet2.cell(15, 5))
    # 获取单元格内容的数据类型
    print(sheet2.cell(15, 5).ctype)


# if __name__ == '__main__':
#     read_excel()
Exemplo n.º 14
0
def image_for_docx(fileref, question, tpl, width=None):
    if fileref.__class__.__name__ in ('DAFile', 'DAFileList', 'DAFileCollection', 'DALocalFile'):
        file_info = dict(fullpath=fileref.path())
    else:
        file_info = server.file_finder(fileref, convert={'svg': 'png'}, question=question)
    if 'fullpath' not in file_info:
        return '[FILE NOT FOUND]'
    if width is not None:
        m = re.search(r'^([0-9\.]+) *([A-Za-z]*)', str(width))
        if m:
            amount = float(m.group(1))
            units = m.group(2).lower()
            if units in ['in', 'inches', 'inch']:
                the_width = Inches(amount)
            elif units in ['pt', 'pts', 'point', 'points']:
                the_width = Pt(amount)
            elif units in ['mm', 'millimeter', 'millimeters']:
                the_width = Mm(amount)
            else:
                the_width = Pt(amount)
        else:
            the_width = Inches(2)
    else:
        the_width = Inches(2)
    return InlineImage(tpl, file_info['fullpath'], the_width)
Exemplo n.º 15
0
def picture(ctx, data, width='40mm', height='40mm', align='center'):
    """
    把图片的二进制数据(使用了base64编码)转化为一个docx.Document对象

    data:图片的二进制数据(使用了base64编码)
    width:图片的宽度,可以为:'12cm','12mm','12pt' 等,参考前面的 calc_length()
    height:图片的长度,如果没有设置,根据长度自动缩放
    align:图片的位置,'left','center','right'
    """

    if not data:
        return None

    if width:
        width = calc_length(width)
    if height:
        height = calc_length(height)

    tempname = tempfile.mkdtemp()
    temppath = os.path.join(
        tempname, 'temp_%s_%s_%s_%s.%s' % (os.getpid(), random.randint(
            1, 10000), ctx.get('id'), ctx.get('create_uid').id, 'png'))
    #data使用了base64编码,所以这里需要解码
    save_file(temppath, data.decode('base64'))
    return InlineImage(ctx['tpl'], temppath, width=width, height=height)
Exemplo n.º 16
0
def add_signature(template, context, signature):
    tmp = DocxTemplate(template)

    img_size = Cm(6.75)  # sets the size of the image
    sign = InlineImage(tmp, signature, img_size)
    context['signature'] = sign  # adds the InlineImage object to the context
    pass
Exemplo n.º 17
0
def word_crate_from_template_with_qrcode(word_file, image_qrcode):
    # https://docxtpl.readthedocs.io/en/latest/
    # https://blog.formpl.us/how-to-generate-word-documents-from-templates-using-python-cb039ea2c890

    #doc = DocxTemplate("./inline_image_tpl.docx")
    doc = DocxTemplate(document_template)

    img_size = Cm(6.75)  # sets the size of the image
    sign = InlineImage(doc, image_qrcode, img_size)

    context = {
        'name': "luca",
        "greetings": "nice dick bro",
        "unit": "345sdfv",
        "arrival": "14/09/2020",
        "deperture": "15/09/2023",
        "saludation": "hasta la proximaa",
        "contact": "Pam Martin, REALTOR",
        "company_name": "Pam Martin - Keller Williams",
        "phone": "(251)269-8864 or (251)279-0717"
    }

    context['qrcode'] = sign  # adds the InlineImage object to the context

    doc.render(context)
    #doc.save("generated_doc.docx")
    doc.save(word_file)
    return word_file
Exemplo n.º 18
0
 def get_table(self, data, tpl):
     images = data['images']
     n_images = len(images)
     n_cols = data['per_row']
     n_rows = math.ceil(n_cols)
     rows = []
     count = 0
     for i in range(n_rows):
         row = []
         for j in range(n_cols):
             if count >= n_images:
                 break
             item = {
                 "caption":
                 images[count]['caption'],
                 "image":
                 InlineImage(tpl,
                             images[count]['path'],
                             width=Pt(images[count]['width']))
             }
             row.append(item)
             count += 1
         if row:
             rows.append(row)
     return rows
Exemplo n.º 19
0
    def generate_course_docx_report(self, _data, _doc_id, filename):
        if _data is None:
            return None
        else:
            # Generate the histogram file
            temp = tempfile.NamedTemporaryFile(prefix="measurement_histogram_",
                                               suffix=".png")
            _grades = _data['fused_grades']
            _total_grades = _grades['totals']
            self.statistics_generate_histogram_course(_total_grades,
                                                      _data['course_name'],
                                                      temp)

            tpl = DocxTemplate(_template_course_report)

            context = {
                'histogram':
                InlineImage(tpl, temp, width=Inches(3), height=Inches(3)),
                'time':
                datetime.datetime.now().strftime("%y-%m-%d, %H:%M:%S"),
                'id':
                str(_doc_id),
            }
            context = {**_data, **context}
            tpl.render(context)
            tpl.save(filename)
            temp.close()
        return filename
Exemplo n.º 20
0
def run_name(name_list, tpl, results_frame):
    for name in name_list:
        results_frame[name]['a'] = round(results_frame[name]['a'][0][0], 2)
        results_frame[name]['b'] = round(results_frame[name]['b'][0], 2)
        results_frame[name]['file_name'] = InlineImage(
            tpl, results_frame[name]['file_name'], Mm(100))
    return results_frame
Exemplo n.º 21
0
def image_for_docx(number, question, tpl, width=None):
    file_info = server.file_finder(number,
                                   convert={'svg': 'png'},
                                   question=question)
    if 'fullpath' not in file_info:
        return '[FILE NOT FOUND]'
    if width is not None:
        m = re.search(r'^([0-9\.]+) *([A-Za-z]*)', str(width))
        if m:
            amount = float(m.group(1))
            units = m.group(2).lower()
            if units in ['in', 'inches', 'inch']:
                the_width = Inches(amount)
            elif units in ['pt', 'pts', 'point', 'points']:
                the_width = Pt(amount)
            elif units in ['mm', 'millimeter', 'millimeters']:
                the_width = Mm(amount)
            else:
                the_width = Pt(amount)
        else:
            the_width = Inches(2)
    else:
        logmessage("err 2")
        the_width = Inches(2)
    return InlineImage(tpl, file_info['fullpath'], the_width)
Exemplo n.º 22
0
 def _get_inline_image(self, file, width=30):
     path = settings.work_dir / file.path
     if path.exists():
         img = InlineImage(self.tpl, str(path), width=Mm(width))
         if img:
             return img
     return "-- Imagem indisponível --"
Exemplo n.º 23
0
def render_template(project, document_template):
    doc = DocxTemplate(document_template.file)

    attribute_data_display = {}
    attributes = {a.identifier: a for a in Attribute.objects.all()}

    for identifier, value in project.get_attribute_data().items():
        attribute = attributes.get(identifier)

        if not attribute:
            continue

        if attribute.value_type == Attribute.TYPE_IMAGE and value:
            display_value = InlineImage(doc, value, width=IMAGE_WIDTH)
        else:
            display_value = attribute.get_attribute_display(value)

        if display_value is None or display_value == "":
            display_value = escape(" < {} >".format(attribute.name))
        elif attribute.value_type == Attribute.TYPE_LONG_STRING:
            display_value = Listing(display_value)

        attribute_data_display[identifier] = display_value

    doc.render(attribute_data_display)
    output = io.BytesIO()
    doc.save(output)
    return output.getvalue()
Exemplo n.º 24
0
 def _get_data(self, message):
     if message.body:
         return message.body
     if message.attachments.count() > 0:
         attachment = message.attachments[0]
         if attachment.type_ == 'audio':
             return '--Mensagem de áudio--'
         if attachment.type_ == 'image':
             return InlineImage(self.tpl, str(settings.work_dir / attachment.path), width=Mm(30))
         if attachment.type_ == 'video':
             if attachment.has_thumb:
                 return InlineImage(self.tpl, str(settings.work_dir / attachment.thumb_path), width=Mm(40))
             else:
                 return "--Video (miniatura não disponível)--"
         return "--Arquivo--"
     return ""
Exemplo n.º 25
0
    def add_chapter(self, chapter, title=None, level=2, remove_file=True):
        try:
            docx = self._doc.get_docx()

            if title is not None:
                docx.add_heading(title, level)

            id = "chapter" + str(self.sequence())

            chapter.render()

            docx.add_paragraph("{{p " + id + "}}")

            self._chapter[id] = self._doc.new_subdoc(chapter.get_filename())

            pic_to_add = chapter.get_pic_to_add()
            if pic_to_add:
                for pic in pic_to_add:
                    path = pic_to_add[pic]["path"]
                    width = pic_to_add[pic]["width"]

                    self._pic_to_render[pic] = InlineImage(self._doc,
                                                           path,
                                                           width=Mm(width))
        finally:
            if remove_file:
                chapter.remove_file()
Exemplo n.º 26
0
def generate_team_roadmaps(target_file):
    files_to_merge = list()
    with tempfile.TemporaryDirectory() as tmpdir:
        for team in Team.objects():
            tpl = DocxTemplate(TEAM_ROADMAP_TEMPLATE)

            qr = pyqrcode.create(team.hash, error=QR_ERROR, version=QR_VERSION)
            qr_file = os.path.join(tmpdir, "team.png")
            qr.png(qr_file,
                   scale=QR_SCALE,
                   module_color=QR_COLOR,
                   quiet_zone=QUIET_ZONE)

            context = dict(section=team.section,
                           teamCode=team.code,
                           qrCode=InlineImage(tpl, qr_file, width=Mm(QR_SIZE)))
            for i, match in enumerate(team.matches, 1):
                game_number = match.game_number
                context["game{}".format(i)] = Game.objects(
                    number=game_number).get().name
                context["gId{}".format(i)] = str(game_number)

            tpl.render(context)
            team_file = os.path.join(tmpdir, "team{}.docx".format(team.code))
            tpl.save(team_file)
            files_to_merge.append(team_file)

        _combine_docx(target_file, files_to_merge)
Exemplo n.º 27
0
def b64_to_inlineimage(context, value):
    b64str = value.split(',', 1)[1]
    decoded = base64.b64decode(b64str)
    tmp_f = NamedTemporaryFile(mode='wb', dir=context['tmpdir'], delete=False)
    tmp_f.write(decoded)
    tmp_f.seek(0)
    return InlineImage(context['tpl'], tmp_f.name, width=Mm(40))
Exemplo n.º 28
0
def word_write(generated_doc_path):
    # 模板路径文件夹
    template_path = current_app.config.get("REPORT_TEMPLATES")
    path = os.path.join(template_path, 'test.docx')

    # 读取指定位置的模板文件
    doc = DocxTemplate(path)
    # 渲染的内容
    context = {
        # 标题
        'title': "人员信息",
        # 表格
        'table': [
            {"name": "小李", "age": 11},
            {"name": "小张", "age": 21},
            {"name": "小张", "age": 20},
            {"name": "小张1", "age": 10},
            {"name": "小张2", "age": 30},
            {"name": "小张3", "age": 40},
        ],
        # 页眉
        'header': 'xxx公司人员信息管理',
        # 页脚
        'footer': '1',
        # 图片
        'image': InlineImage(doc, os.path.join(template_path, 'test.jpg'), height=Mm(10)),
    }
    # 渲染模板
    doc.render(context)

    # 保存渲染的文件
    doc.save(generated_doc_path)
    return generated_doc_path
Exemplo n.º 29
0
 def get_typical_peptide_map(self, select_chain, report_path):
     temp = select_chain.find_all('div', {'class': "support-spectra"})[0]
     discription = []
     img = []
     stop_flag = 0
     for i in range(int(len(temp.find_all('span')) / 2)):
         if int(
                 temp.find_all('span')[2 * i].get_text().split()[1].split(
                     '-')[0]) < 151:
             stop_flag = i
         discription.append(" ".join([
             temp.find_all('span')[2 * i].get_text(),
             temp.find_all('span')[2 * i + 1].get_text()
         ]))
     for i in temp.find_all('img'):
         img.append(i.get('src')[4:])
     map_format = []
     for i in range(stop_flag):
         map_format.append({
             'title':
             discription[i],
             'img':
             InlineImage(self.tpl,
                         path.join(report_path, 'img', img[i]),
                         width=Mm(165),
                         height=Mm(84.9))
         })
     return map_format
Exemplo n.º 30
0
def generatereport_ds():
    filename = report_name  # 所生成的word文档需要以.docx结尾,文档格式需要
    filepath = path_name

    template_path = os.getcwd() + '/test.docx'  #加载模板文件
    template = DocxTemplate(template_path)
    if os.path.exists(img_name) == False:  #判断下面代码使用的图片是否存在,不存在则调用函数生成
        plt_fc(img_name)
    context = {
        'text': '哈哈哈,来啦',
        't1': '燕子',
        't2': '杨柳',
        't3': '桃花',
        't4': '针尖',
        't5': '头涔涔',
        't6': '泪潸潸',
        't7': '茫茫然',
        't8': '伶伶俐俐',
        'picture1': InlineImage(template,
                                img_name,
                                width=Mm(80),
                                height=Mm(60)),
    }

    user_labels = ['姓名', '年龄', '性别', '入学日期']
    context['user_labels'] = user_labels
    user_dict1 = {'number': 1, 'cols': ['林小熊', '27', '男', '2019-03-28']}
    user_dict2 = {'number': 2, 'cols': ['林小花', '27', '女', '2019-03-28']}
    user_list = []
    user_list.append(user_dict1)
    user_list.append(user_dict2)

    context['user_list'] = user_list
    template.render(context)
    template.save(os.path.join(filepath, filename))