Esempio n. 1
0
def add_table_merge(path, data, merges, widths=[]):
    '''
    创建表格
    '''
    logger.info('--生成合并表格{}'.format(datetime.now()))
    labels = data['labels']
    rows = data['data']
    docx = Document()
    style = docx.styles['Table Grid']
    table = docx.add_table(rows=1 + len(rows), cols=len(labels), style=style)
    # 自定义表格宽度
    if widths:
        table.autofit = False  # 很重要!
        for row in range(1 + len(rows)):
            for index, w in enumerate(widths):
                table.cell(row, index).width = Inches(float(w))
    # 生成表头
    hdr_cells = table.rows[0].cells
    for index, value in enumerate(labels):
        if not isinstance(value, unicode):
            value = unicode(value, "utf-8")
        hdr_cells[index].text = value
    format_data = formate_table_merge_data(data=rows, merges=merges)
    logger.info('--格式化表格数据{}'.format(datetime.now()))
    # 生成表格内容
    create_docx_table_body(docx=docx,
                           path=path,
                           table=table,
                           data=format_data,
                           merges=merges)
    logger.info('--合并表格完成{}'.format(datetime.now()))
    docx.save(path)
    return path
Esempio n. 2
0
def include_docx_template(template_file, **kwargs):
    """Include the contents of one docx file inside another docx file."""
    if this_thread.evaluation_context is None:
        return 'ERROR: not in a docx file'
    if template_file.__class__.__name__ in ('DAFile', 'DAFileList', 'DAFileCollection', 'DALocalFile'):
        template_path = template_file.path()
    else:
        template_path = package_template_filename(template_file, package=this_thread.current_package)
    sd = this_thread.misc['docx_template'].new_subdoc()
    sd.subdocx = Document(template_path)

    # We need to keep a copy of the subdocs so we can fix up the master template in the end (in parse.py)
    # Given we're half way through processing the template, we can't fix the master template here
    # we have to do it in post
    if 'docx_subdocs' not in this_thread.misc:
        this_thread.misc['docx_subdocs'] = []
    this_thread.misc['docx_subdocs'].append(deepcopy(sd.subdocx))

    # Fix the subdocs before they are included in the template
    fix_subdoc(this_thread.misc['docx_template'], sd.subdocx)

    first_paragraph = sd.subdocx.paragraphs[0]
    for key, val in kwargs.items():
        if hasattr(val, 'instanceName'):
            the_repr = val.instanceName
        else:
            the_repr = '_codecs.decode(_array.array("b", "' + re.sub(r'\n', '', codecs.encode(bytearray(val, encoding='utf-8'), 'base64').decode()) + '".encode()), "base64").decode()'
        first_paragraph.insert_paragraph_before(str("{%%p set %s = %s %%}" % (key, the_repr)))
    if 'docx_include_count' not in this_thread.misc:
        this_thread.misc['docx_include_count'] = 0
    this_thread.misc['docx_include_count'] += 1
    return sd
Esempio n. 3
0
def include_docx_template(template_file, **kwargs):
    """Include the contents of one docx file inside another docx file."""
    if this_thread.evaluation_context is None:
        return 'ERROR: not in a docx file'
    if template_file.__class__.__name__ in ('DAFile', 'DAFileList',
                                            'DAFileCollection'):
        template_path = template_file.path()
    else:
        template_path = package_template_filename(
            template_file, package=this_thread.current_package)
    sd = this_thread.docx_template.new_subdoc()
    sd.subdocx = Document(template_path)
    sd.subdocx._part = sd.docx._part
    first_paragraph = sd.subdocx.paragraphs[0]
    for key, val in kwargs.iteritems():
        if hasattr(val,
                   'instanceName') and val.__class__.__name__.startswith('DA'):
            the_repr = val.instanceName
        else:
            the_repr = '"' + re.sub(
                r'\n', '',
                unicode(val).encode('utf-8').encode(
                    'base64')) + '".decode("base64").decode("utf-8")'
        first_paragraph.insert_paragraph_before(
            str("{%%p set %s = %s %%}" % (key, the_repr)))
    this_thread.docx_include_count += 1
    return sd
Esempio n. 4
0
def include_docx_template(template_file, **kwargs):
    """Include the contents of one docx file inside another docx file."""
    if this_thread.evaluation_context is None:
        return 'ERROR: not in a docx file'
    if template_file.__class__.__name__ in ('DAFile', 'DAFileList',
                                            'DAFileCollection', 'DALocalFile'):
        template_path = template_file.path()
    else:
        template_path = package_template_filename(
            template_file, package=this_thread.current_package)
    sd = this_thread.misc['docx_template'].new_subdoc()
    sd.subdocx = Document(template_path)
    sd.subdocx._part = sd.docx._part
    first_paragraph = sd.subdocx.paragraphs[0]
    for key, val in kwargs.items():
        if hasattr(val, 'instanceName'):
            the_repr = val.instanceName
        else:
            the_repr = '_codecs.decode(_array.array("b", "' + re.sub(
                r'\n', '',
                codecs.encode(
                    bytearray(val, encoding='utf-8'),
                    'base64').decode()) + '".encode()), "base64").decode()'
        first_paragraph.insert_paragraph_before(
            str("{%%p set %s = %s %%}" % (key, the_repr)))
    if 'docx_include_count' not in this_thread.misc:
        this_thread.misc['docx_include_count'] = 0
    this_thread.misc['docx_include_count'] += 1
    return sd
Esempio n. 5
0
def create_sub_docx(doc, sub_docx_name, table_data, merges, widths):
    '''
    生成子文档
    '''
    path = os.path.join('media', 'reports', 'tmp_docx',
                        '{}.docx'.format(sub_docx_name))
    sub_path = add_table_merge(path=path,
                               data=table_data,
                               merges=merges,
                               widths=widths)
    sub = doc.new_subdoc()
    sub.subdocx = Document(sub_path)
    return sub
Esempio n. 6
0
def include_docx_template(template_file, **kwargs):
    """Include the contents of one docx file inside another docx file."""
    use_jinja = kwargs.get('_use_jinja2', True)
    if this_thread.evaluation_context is None:
        return 'ERROR: not in a docx file'
    if template_file.__class__.__name__ in ('DAFile', 'DAFileList', 'DAFileCollection', 'DALocalFile', 'DAStaticFile'):
        template_path = template_file.path()
    else:
        template_path = package_template_filename(template_file, package=this_thread.current_package)
    sd = this_thread.misc['docx_template'].new_subdoc()
    sd.subdocx = Document(template_path)
    if not use_jinja:
        return sanitize_xml(str(sd))
    if '_inline' in kwargs:
        single_paragraph = True
        del kwargs['_inline']
    else:
        single_paragraph = False
    if 'change_numbering' in kwargs:
        change_numbering = bool(kwargs['change_numbering'])
        del kwargs['change_numbering']
    else:
        change_numbering = True

    # We need to keep a copy of the subdocs so we can fix up the master template in the end (in parse.py)
    # Given we're half way through processing the template, we can't fix the master template here
    # we have to do it in post
    if 'docx_subdocs' not in this_thread.misc:
        this_thread.misc['docx_subdocs'] = []
    this_thread.misc['docx_subdocs'].append({'subdoc': deepcopy(sd.subdocx), 'change_numbering': change_numbering})

    # Fix the subdocs before they are included in the template
    fix_subdoc(this_thread.misc['docx_template'], {'subdoc': sd.subdocx, 'change_numbering': change_numbering})

    first_paragraph = sd.subdocx.paragraphs[0]
    for key, val in kwargs.items():
        if hasattr(val, 'instanceName'):
            the_repr = val.instanceName
        else:
            the_repr = '_codecs.decode(_array.array("b", "' + re.sub(r'\n', '', codecs.encode(bytearray(val, encoding='utf-8'), 'base64').decode()) + '".encode()), "base64").decode()'
        first_paragraph.insert_paragraph_before(str("{%%p set %s = %s %%}" % (key, the_repr)))
    if 'docx_include_count' not in this_thread.misc:
        this_thread.misc['docx_include_count'] = 0
    this_thread.misc['docx_include_count'] += 1
    if single_paragraph:
        return re.sub(r'<w:p[^>]*>\s*(.*)</w:p>\s*', r'\1', str(first_paragraph._p.xml), flags=re.DOTALL)
    return sd
Esempio n. 7
0
def createSaveDoc(updatedEmail):
    def checkDuplicateTitle(title):
        for root, dirs, files in os.walk(os.getcwd()):
            match = 0
            for name in files:
                matchobj = re.match(title, name)
                if matchobj:
            print(match)
            return match
    document = Document()  # creates doc object
    document.add_paragraph(updatedEmail)  # adds string to doc
    titleOfDoc = "MPPG credentials for " + getNameOfSite(updatedEmail) + ' ' + getCity(updatedEmail)
    match = checkDuplicateTitle(titleOfDoc)
    if match == 0:
        document.save(titleOfDoc + '.docx')
    else:
        titleOfDoc = (titleOfDoc + ' (' + str(match) + ')' + '.docx')
        document.save(titleOfDoc)