Example #1
0
def txtchangepicture(docpath, sel_str, imgpath):
    # 替换文本为模板对象
    document = Document(docpath)
    for para in document.paragraphs:
        if sel_str in para.text:
            inline = para.runs
            for i in inline:
                if sel_str in i.text:
                    if "{{%s}}" % sel_str not in i.text:
                        text = i.text.replace(sel_str, "{{%s}}" % sel_str)
                        i.text = text

    document.save(docpath)

    tpl = DocxTemplate(docpath)
    context = {
        sel_str:InlineImage(tpl, imgpath, width=Mm(20)),
    }
    tpl.render(context)
    date = datetime.datetime.now()
    filepath = __file__
    realpath = os.path.realpath(filepath)
    current_path = os.path.dirname(realpath)
    path = os.path.join(current_path, "%s%s%s" % (date.year, date.month, date.day))
    if not os.path.exists(path):
        os.mkdir(path)
    filepath = os.path.join(path, "%s%s%s.docx" % (date.hour, date.minute, date.second))
    tpl.save(filepath)
Example #2
0
async def get_info(x: dict, image: str):
    locale.setlocale(locale.LC_ALL, 'ru_RU')
    doc = DocxTemplate(
        os.path.join(BASE_DIR, 'data',
                     'Reshenie_edinstvennogo_uchreditelja.docx'))
    morph = pymorphy2.MorphAnalyzer()
    e = ''
    for word in x.get('ФИО').split(" "):
        e += str("".join(morph.parse(word)[0].inflect({'gent'}).word.title()) +
                 " ")
    context = {
        "Image":
        InlineImage(doc,
                    os.path.join(BASE_DIR, 'excel', f"V{2 + int(image)}.png"),
                    width=Mm(40)),
        "НАЗВАНИЕ":
        x.get("Фирма").strip(),
        "ЮР_ГОР":
        x.get("Юр. Адрес"),
        "ДАТА":
        datetime.today().strftime("%d %B %Y года."),
        "ФИО":
        x.get("ФИО"),
        "НОМЕР_УСТАВА":
        x.get("НОМЕР.УСТАВА"),
        "ИНН":
        x.get("ИНН"),
        "СУММ_ПРО":
        x.get("Уст.Кап")
    }

    doc.render(context)
    doc.save(os.path.join(BASE_DIR, 'excel', f'{x.get("Фирма").strip()}.docx'))
    return f'{x.get("Фирма").strip()}.docx'
    def make_report(self):
        print('Building report...')
        doc = docxtpl.DocxTemplate(density_report_template)
        styles = doc.styles
        date_now = datetime.today().strftime('%c')
        basic_info_table = self.make_table_doco(
            self.information_table.round(3), 'Summary')

        histo_inline = docxtpl.InlineImage(doc, self.histo_out)
        density_im_inline = docxtpl.InlineImage(doc,
                                                self.image_path,
                                                height=Mm(180))

        context = {
            'br_code': self.br_code,
            'area_name': self.area_name,
            'date_gen': date_now,
            'cov_w_aoi': density_im_inline,
            'histo': histo_inline,
            'dens_table': basic_info_table,
            'user': self.user,
            'method': self.method,
            'cell_count': self.compliant_cells,
            'cell_sq': self.cell_size * self.cell_size
        }
        doc.render(context)
        doc.save(self.report_path)
        print('Wrote %s...' % os.path.basename(self.report_path))
Example #4
0
def image_for_docx(fileref, question, tpl, width=None):
    if fileref.__class__.__name__ in ('DAFile', 'DAFileList',
                                      'DAFileCollection', 'DALocalFile',
                                      'DAStaticFile'):
        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)
            elif units in ['cm', 'centimeter', 'centimeters']:
                the_width = Cm(amount)
            elif units in ['twp', 'twip', 'twips']:
                the_width = Twips(amount)
            else:
                the_width = Pt(amount)
        else:
            the_width = Inches(2)
    else:
        the_width = Inches(2)
    return InlineImage(tpl, file_info['fullpath'], the_width)
Example #5
0
    def _set_page_settings(self):
        """Changes the page settings."""

        sections = self._document.sections

        for section in sections:
            # Page size
            section.page_width = Mm(210)
            section.page_height = Mm(270)

            # Margin
            margin = Cm(2.5)
            section.top_margin = margin
            section.bottom_margin = margin
            section.left_margin = margin
            section.right_margin = margin
Example #6
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)
Example #7
0
def generate_doc(formato, id):
    docform = "doc/" + formato + ".docx"
    exec("qry2 = db_session.query(" + formato + ").filter(" + formato +
         ".id==int(id)).first()")
    #    qry3 = locals()['qry2']
    #    list1 = [x for x in qry3.items.split(' ') if x]
    #    [{"descripcion":x,"cable":"4/0 - 4/0","metal":"250"} for x in list1 if x=="s3"]
    doc = DocxTemplate(docform)
    fid = id.zfill(3)
    fform = formato[1:]
    name = fform + fid
    EAN = barcode.get_barcode_class('ean8')
    ean = EAN(name + '0', writer=ImageWriter())
    pngname = ean.save('ean8_1')
    image = cv2.imread(pngname)
    cv2.imwrite(pngname, image[20:100, :, 2])
    context = {
        'f': locals()['qry2'],
        'bcean8': InlineImage(doc, pngname, width=Mm(40))
    }
    doc.render(context)
    filename = "temp/temp.docx"
    doc.save(filename)
    fname = name + ".docx"
    qry3 = locals()['qry2']
    return filename, fname, qry3
Example #8
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)
Example #9
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
Example #10
0
 def replaceKeywordByImages(self, keyword, images, width=None, height=None):
     for paragraph in self.doc.paragraphs:
         if keyword in paragraph.text.strip():
             paragraph.text = ''
             for image in images:
                 run = paragraph.add_run()
                 if width and height:
                     run.add_picture(image,
                                     width=Mm(width),
                                     height=Mm(height))
                 elif width:
                     run.add_picture(image, width=Mm(width))
                 elif height:
                     run.add_picture(image, height=Mm(height))
                 else:
                     run.add_picture(image)
Example #11
0
def generatereport(request):
    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()
    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))
    response = StreamingHttpResponse(
        read_file(os.path.join(filepath, filename), 512))
    response['Content-Type'] = 'application/msword'  #msword是输出word文件
    #    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment;filename="{}"'.format(
        filename)
    # time.sleep(10)
    if os.path.exists(filename):
        data = {'code': 200, 'msg': 'success!', 'report_name': filename}
        return HttpResponse(json.dumps(data), content_type='application/json')
    else:
        return HttpResponse('报告生成失败!')
Example #12
0
    def get_print_context_data(self, **kwargs):
        context = super().get_print_context_data(**kwargs)
        context['object'] = self.get_object()

        # добавим штрих-код заявки
        direction_barcode_path = core.datatools.barcode.create_jpg(
            context['object'].number,
            tmp_dir=tempfile.mkdtemp(dir=settings.DIR_FOR_TMP_FILES),
            module_height=5,
            write_text=False)
        context['images'] = {
            'direction_barcode':
            core.generic.mixins.DocxImage(direction_barcode_path,
                                          width=Mm(40),
                                          height=Mm(15))
        }
        return context
Example #13
0
def changeValues(save_location, bracket_type, values):
    # Import Template
    template = DocxTemplate(ROOT_DIR + '\\ReportFiles\\Templates\\' +
                            bracket_type + '.docx')
    # Date
    x = datetime.datetime.now()
    hz_table, psac, wsac, snr = report_output(ROOT_DIR +
                                              "\\ReportFiles\\rt_calc.xlsm")
    # TODO: Gather actual values.
    context = {
        'report_number':
        values[0],
        'issue_date':
        str(x.day) + '/' + str(x.month) + '/' + str(x.year),
        'test_date':
        str(x.day) + '/' + str(x.month) + '/' + str(x.year),
        'client':
        values[1],
        'specimen_name':
        values[2],
        'specimen_desc':
        values[3],
        'A':
        values[4],
        'B':
        values[5],
        'C':
        values[6],
        'temperature':
        values[7],
        'humidity':
        values[8],
        'pressure':
        values[9],
        'hz':
        hz_table,
        'psac':
        psac,
        'wsac':
        wsac,
        'snr':
        snr,
        'chart':
        InlineImage(template,
                    ROOT_DIR + '\\ReportFiles\\chartImage.png',
                    width=Mm(105))
    }
    print(context)
    # Apply Values
    template.render(context)
    # Save Template
    template.save(save_location + '\\Report.docx')


# full_values(ROOT_DIR + "/ReportFiles/NO_SAMPLE.csv")
# update_excel(ROOT_DIR + "\\ReportFiles\\rt_calc.xlsm")
# values = get_excel(ROOT_DIR + "\\ReportFiles\\rt_calc.xlsm")
# print(values)
Example #14
0
def create_name_table_tags_docx_for_guests_who_confirmed():
    all_guests = wgd.generate_names_dict(wgd.extract_guests_from_wedding_sheet())
    if all_guests is None:
        raise Exception('guests_dict is empty!')    
    # extract people who confirmed attending at wedding party
    confirmed_list = []
    for i, _ in enumerate(all_guests ['name']):
        if all_guests ['invited'][i] == 'T' and all_guests ['confirmed'][i] == 'T':
            confirmed_list.append({'name':all_guests ['name'][i],
                                   'surname':all_guests ['surname'][i]}) 
    


    # create doc
    doc = Document()
    cols_num = 2
    table = doc.add_table(rows=0, cols=cols_num)
    table.alignment = WD_TAB_ALIGNMENT.CENTER
    table.style = 'Table Grid'
    for i in range(0, len(confirmed_list), cols_num):
        row = table.add_row()
        # set cell width and height
        for cell in row.cells:
            cell.width  = Mm(80)
            cell.height = Mm(55)
        for col_num in range(cols_num):
            prgs = row.cells[col_num].paragraphs
            img_width = Mm(70)
            img_height = Mm(15)
            prgs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
            prgs[0].add_run().add_picture('flowers_name_tag_up.png', height=img_height, width=img_width)
            text_run = prgs[0].add_run()
            text_run.font.size = Pt(14)
            text_run.font.name = 'Cambria'
            text_run.bold = True
            text_run.italic = True
            try:
                text_run.add_text('{} {}'.format(confirmed_list[i]['name'], confirmed_list[i]['surname']))
            except:
                pass
            prgs[0].add_run().add_picture('flowers_name_tag_down.png', height=img_height, width=img_width)
            i = i+1

    doc.add_page_break()
    doc.save("table_name_tags.docx")
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
def get_page_size(section):
    width = round(section.page_width, -4)
    if width == round(Mm(210), -4):
        return 'A4'
    elif width == round(Inches(8.5), -4):
        return 'Letter'
    else:
        mm = round(round(width, -4) / 36000, 2)
        return f'Unknown page size with width {mm} mm'
Example #17
0
def get_name_to_setpictosrc(check_app,tpl,filelists,file_path,use_tab = ''):
    context_pic = {}
    target_name = ''
    if filelists:
        for file_count,file_name in enumerate(filelists):
            file_path_output = '././Report'+file_path+'/pic/'+filelists[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))

            for key_name,value_name in file_name.items():
                if(key_name in file_path_output):
                    target_name = value_name
            context_pic.update({target_name:context_pic_value})
    return(context_pic)
def clusterDocument(document, list1, list2):
    h1 = document.add_heading('2.集群巡检')
    count = 0
    text = ''
    for i in list2:
      if i:
          count += 1
    p1 = document.add_paragraph()
    run1 = p1.add_run("巡检小结:")
    run1.font.name = u'宋体'
    run1.font.size = Pt(11)
    text = "对集群虚拟化进行巡检,巡检异常项数:" + (str)(count) + ";" + "正常项数:" + (str)(len(list2) - count)
    p2 = document.add_paragraph()
    p2.paragraph_format.first_line_indent = Inches(0.3)
    run2 = p2.add_run(text)
    run2.font.name = u'宋体'
    run2.font.size = Pt(11)

    t1 = createTable(document, 7, 4)
    # 初始化表格
    t1.cell(0, 0).text = "检查内容"
    t1.cell(0, 1).text = "检查方法"
    t1.cell(0, 2).text = "检查结果"
    t1.cell(0, 3).text = "说明"
    t1.cell(1, 0).text = "集群高可靠性(HA)功能:查看集群的高可靠性(HA)功能是否正常开启"
    t1.cell(1, 1).text = "在<云资源>/<主机池>/<集群>的“高可靠性”页面检查是否选择了“启用HA”"
    t1.cell(2, 0).text = "集群动态资源调度(DRS)功能:查看集群的动态" \
                         "资源调度(DRS)功能是否正常开启"
    t1.cell(2, 1).text = "在<云资源>/<主机池>/<集群>的“动态资源调度”" \
                         "页面检查是否选择了“开启动态资源调度”"
    t1.cell(3, 0).text = "集群下虚拟交换机分配:查" \
                         "看集群下虚拟交换机的分配情况。"
    t1.cell(3, 1).text = "在<云资源>/<主机池>/<主机>的“虚拟交" \
                         "换机”页面检查集群下的所有主机是否都" \
                         "有相同名称的虚拟交换机"
    t1.cell(4, 0).text = "集群下共享存储分配:" \
                         "查看集群下共享存储的分配情况"
    t1.cell(4, 1).text = "在<云资源>/<主机池>/<集群>的“存储”" \
                         "页面检查集群下的主机是否都分配了相同的共享存储"
    t1.cell(5, 0).text = "集群下共享存储使用率:查看集群下共享存" \
                         "储的实际使用情况,实际使用率超过70%标记为不" \
                         "正常。实际使用率超过90%,标记为平台重大风险项。"
    t1.cell(5, 1).text = "在<云资源>/<主机池>/<集群>的“存储”页面检" \
                         "查集群下的共享存储可用容量"
    t1.cell(6, 0).text = "集群高可靠性生效最小节点数:查看集群中正常运行的主机数量不少于“HA生效最小节点数”"
    t1.cell(6, 1).text = "在<云资源>/<主机池>/<集群>的“高可靠性”页面检查“HA生效最小节点数”和集群内正常运行的主机数量"

    t1.columns[2].width = Mm(20)
    # 参数赋值
    for i in range(6):
        if not list2[i]:
            t1.cell(i + 1, 2).paragraphs[0].add_run(list1[i])
        else:
            run = t1.cell(i + 1, 2).paragraphs[0].add_run(list1[i])
            run.font.color.rgb = RGBColor(255, 0, 0)
            t1.cell(i + 1, 3).paragraphs[0].add_run(list2[i])
    return
Example #19
0
def saveSBAR(report_doc, name):
    section = report_doc.sections[0]
    section.page_height = Mm(210)
    section.page_width = Mm(297)
    section.left_margin = Mm(10)
    section.right_margin = Mm(10)
    section.top_margin = Mm(55)
    section.bottom_margin = Mm(10)
    section.header_distance = Mm(28)
    section.footer_distance = Mm(12)
    filenameout = 'C:/PyCharmProjects/assets/report_%s_%s.docx' % name
    report_doc.save(filenameout)
Example #20
0
def image(ctx, img_name, width=None, height=None):
    tpl = ctx["_tpl"]

    if img_name not in ctx:
        raise ValidationError(f'No file for image "{img_name}" provided!')

    img = ctx.get(img_name)

    if not img:
        # Fallback to no image
        return

    img.seek(0)  # needed in case image is referenced multiple times
    if imghdr.what(img) not in ["png", "jpg", "jpeg"]:
        raise ValidationError("Only png and jpg images are supported!")

    width = Mm(width) if width else None
    height = Mm(height) if height else None
    return InlineImage(tpl, img, width=width, height=height)
Example #21
0
    def _attchments(self):
        generator = ParagraphGenerator() \
            .alignment(ParagraphGenerator.ALIGN_LEFT) \
            .line_spacing(18) \
            .space_after(6)

        images = Image.objects.only("id").filter(factory=self.factory)
        for index, image in enumerate(images, start=1):
            generator.new(self.document, f"附件 {to_lower_chinese_numbers(index)}", 12)
            data = urlopen(image.image_path).read()

            image_data = PIL.Image.open(BytesIO(data))
            if image_data.format == "JPEG":
                # Use PIL to save all jpeg files again to workaround python-docx bug
                # https://github.com/python-openxml/python-docx/issues/187
                tmp_image_data = BytesIO()
                image_data.save(tmp_image_data, format="jpeg")
                self.document.add_picture(tmp_image_data, width=Mm(150))
            else:
                self.document.add_picture(BytesIO(data), width=Mm(150))
Example #22
0
    def build_word(self, image_path):
        doc_path = os.path.join(
            os.path.dirname(image_path),
            os.path.basename(image_path) + ".docx")
        print(doc_path)
        imagefiles = []
        for file in glob.glob(os.path.join(image_path,"*.jpg")):
            imagefiles.append(file)
        print(len(imagefiles))

        top_margin = Mm(5.1)
        left_margin = Mm(6.1)
        page_height = Mm(210)
        page_width = Mm(297)
        header_distance = Mm(0)
        footer_distance = Mm(0)
        image_height = Mm(210 - 2 * 5.1)
        image_width = Mm(148.5 - 6.1)

        document = Document()
        section = document.sections[0]
        section.orientation = WD_ORIENT.LANDSCAPE
        section.page_height = page_height
        section.page_width = page_width
        section.top_margin = top_margin
        section.bottom_margin = top_margin
        section.left_margin = left_margin
        section.right_margin = left_margin
        section.header_distance = header_distance
        section.footer_distance = footer_distance

        new_paragraph = True

        for image in imagefiles:
            if new_paragraph:
                paragraph = document.add_paragraph()
                paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
            new_paragraph = not new_paragraph
            run = paragraph.add_run()
            run.add_picture(image, height=image_height) #, width=image_width)

        # sections = document.sections
        # for section in sections:
        #     section.orientation = WD_ORIENT.LANDSCAPE
        #     section.top_margin = top_margin
        #     section.bottom_margin = top_margin
        #     section.left_margin = left_magrin
        #     section.right_margin = left_magrin

        document.save(doc_path)
        print("done")
Example #23
0
def load_image(template, image_file=PORTRAIT_FILE_PREFIX, **kwargs):
    if image_file == PORTRAIT_FILE_PREFIX:
        for ext in ('jpg', 'jpeg', 'png'):
            image_file = f'{image_file}.{ext}'
            if os.path.exists(image_file):
                break
        else:
            print(f'No portrait image file found')
            sys.exit(1)
    elif not os.path.exists(image_file):
        print(f'Portrait file `{image_file}` not found')
    return VersentInlinePortrait(template, image_file, width=Mm(66))
Example #24
0
def fp_to_docx(fp_object, template, out_folder, doc_name):
    from docx.shared import Mm, Inches
    from os.path import join
    doc_template = docxtpl.DocxTemplate(template)
    in_vars = doc_template.get_undeclared_template_variables()
    dict_vars = {}
    for var in in_vars:
        try:
            if fp_object.fm_main[var]['domain_trans']:
                try:
                    dict_vars[var] = fp_object.fm_main[var]['domain_trans'][
                        fp_object.attributes[var]]
                except KeyError:
                    dict_vars[var] = fp_object.attributes[var]
            else:
                dict_vars[var] = fp_object.attributes[var]
        except KeyError:
            if 'att' in var:
                print('\tattachment {}'.format(var))
                if 'att20_' in var:
                    att_url = find_attachment(fp_object.att_res,
                                              var.replace('att20_', ''))
                    if att_url == None:
                        pass
                    else:
                        dict_vars[var] = docxtpl.InlineImage(
                            doc_template,
                            set_up_docx_inline(att_url),
                            height=Mm(20))
                else:
                    att_url = find_attachment(fp_object.att_res,
                                              var.replace('att_', ''))
                    if att_url == None:
                        pass
                    else:
                        dict_vars[var] = docxtpl.InlineImage(
                            doc_template,
                            set_up_docx_inline(att_url),
                            width=Inches(6))
            elif 'rel_' in var:
                related_set = find_related_table(fp_object,
                                                 var.replace('rel_', ''))
                if len(related_set.features) > 0:
                    dict_vars[var] = related_set.return_sdf().to_dict(
                        'records')

            else:
                print('\tnon-attribute: {}'.format(var))
    doc_template.render(dict_vars)
    if '.docx' not in doc_name:
        doc_name = doc_name + '.docx'
    print('\tsaving...')
    return doc_template.save(join(out_folder, doc_name))
Example #25
0
def GenerateWordReport(VulnerabilityDataList, **kwargs):
    #读取模板文档
    try:
        tpl = DocxTemplate(GetTemplateFolderLocation().Result() +
                           'WordTemplate.docx')
        Vulnerabulity = []
        scheme, url, port = UrlProcessing().result(kwargs.get("target_url"))

        VulnerabilityNumber = 0  #计算漏洞个数用最后清零
        for i in VulnerabilityDataList:
            VulnerabilityNumber += +1  #自增
            Vulnerabulity.append({
                'vulnerability_name':
                i.get("vulnerability_name"),  #漏洞名称
                'vulnerability_level':
                i.get("vulnerability_level"),  #漏洞级别
                'find_the_time':
                i.get("find_the_time"),  #发现时间
                'vulnerability_description':
                i.get("vulnerability_description"),  #漏洞描述
                'vulnerability_details':
                str(base64.b64decode(i.get("vulnerability_details")),
                    encoding='utf-8'
                    ),  #.replace("\r\n","\a"),#漏洞细节,在word中\r\n需要替换成^l^p
                'vulnerability_number':
                VulnerabilityNumber,
                'repair_suggestions':
                i.get("repair_suggestions")  #修复建议
            })
        context = {
            'target_url':
            scheme + "://" + url,  #传入处理过的URL
            'number_of_vulnerabilities_in_the_target_website':
            VulnerabilityNumber,
            'home_picture':
            InlineImage(tpl,
                        GetTemplateFolderLocation().Result() +
                        "home_picture.jpg",
                        width=Mm(120)),
            'vulnerability':
            Vulnerabulity,
            'report_export_time':
            int(time.time()),
        }
        tpl.render(context)
        WordName = str(int(
            time.time())) + "_" + url + '.docx'  #生成报告名字,这边经过处理不然Windows报错
        tpl.save(GetDownloadFolderLocation().Result() + WordName)
        VulnerabilityNumber = 0
        return WordName  #返回模板名字
    except Exception as e:
        ErrorLog().Write("Web_Api_ProcessingReport_GenerateWordReport(def)", e)
        return None
Example #26
0
    def callPrinterToPrint(self, stringToPrint):
        document = docx.Document()
        margin = 5
        sections = document.sections
        for section in sections:
            section.page_height = Mm(210)
            section.page_width = Mm(72)
            section.top_margin = Mm(margin)
            section.bottom_margin = Mm(margin)
            section.left_margin = Mm(margin)
            section.right_margin = Mm(margin)

        document.add_paragraph(stringToPrint)
        document.save("testdoc.docx")
        try:
            print("Start printing...")
            os.startfile("testdoc.docx", "print")
            time.sleep(1)
            os.startfile("testdoc.docx", "print")
            time.sleep(1)
            print("Done!")
        except Exception as e:
            print(str(e))
            print("--Failed to print--")
            time.sleep(2)
Example #27
0
 def __doc_settings(self):
     section = self.__doc.sections[0]
     section.page_height = Mm(297)
     section.page_width = Mm(210)
     section.left_margin = Mm(5)
     section.right_margin = Mm(5)
     section.top_margin = Mm(5)
     section.bottom_margin = Mm(5)
     section.header_distance = Mm(5)
     section.footer_distance = Mm(5)
     style = self.__doc.styles['Normal']
     font = style.font
     font.name = 'Calibri'
     font.size = Pt(8)
    async def make_resheie(self, context: dict, image: int, file='Reshenie.docx'):
        file_path = await self.make_folder(context.get('НАЗВАНИЕ'))
        write_resh = DocxTemplate(join(self.path, 'files', 'templates', file))
        context["Image"] = InlineImage(write_resh, join(self.path, 'files', 'TEMP', f"B{2 + int(image)}.png"),
                                       width=Mm(40))
        write_resh.render(context=context)
        if file == "Reshenie.docx":

            file = f'РЕШЕНИЕ_{context["НАЗВАНИЕ"]}.docx'
        else:
            file = f'ПРИКАЗ_{context["НАЗВАНИЕ"]}.docx'
        write_resh.save(join(file_path, file))
        return join(file_path, file)
Example #29
0
 def fill_msiimage(self):
     meta_csvFile = codecs.open(
         "/disk/lulu/autoreport/material/metadate.csv", "r", 'gbk')
     reader = csv.DictReader(meta_csvFile)
     global given_id
     global context
     sample_id = []
     MSI_path = []
     global context
     for row in reader:
         sample_id.append(row['样本编号'])
         MSI_path.append(row['MSI_PCR图路径'])
     if given_id in sample_id:
         position = sample_id.index(given_id)
     realMSI_path = MSI_path[position]
     print(realMSI_path)
     meta_csvFile.close()
     realMSI_pathvalue = InlineImage(doc,
                                     realMSI_path,
                                     height=Mm(67),
                                     width=Mm(146.4))
     context['msiimage'] = realMSI_pathvalue
def createTable(document, row, col):
    # table = document.add_table(row, col, style='Medium Grid 1 Accent 1')
    table = document.add_table(row, col, style='Table Grid')
    table.style.font.name = u'宋体'
    table.style.font.size = Pt(11)
    for i in table.rows[0].cells:
        shading_elm_2 = parse_xml(r'<w:shd {} w:fill="B0C4DE"/>'.format(nsdecls('w')))
        i._tc.get_or_add_tcPr().append(shading_elm_2)
        del shading_elm_2
    # table = document.add_table(row, col, style='Medium Shading 2 Accent 1')
    for i in table.rows:
        i.height = Mm(10)
    return table