コード例 #1
0
def simpledoc(noimagecopy=False):
    """Make a docx (document, relationships) for use in other docx tests"""
    relationships = relationshiplist()
    imagefiledict = {}
    document = newdocument()
    docbody = document.xpath('/w:document/w:body', namespaces=nsprefixes)[0]
    docbody.append(heading('Heading 1', 1))
    docbody.append(heading('Heading 2', 2))
    docbody.append(paragraph('Paragraph 1'))
    for point in ['List Item 1', 'List Item 2', 'List Item 3']:
        docbody.append(paragraph(point, style='ListNumber'))
    docbody.append(pagebreak(type='page'))
    docbody.append(paragraph('Paragraph 2'))
    docbody.append(
        table([['A1', 'A2', 'A3'], ['B1', 'B2', 'B3'], ['C1', 'C2', 'C3']]))
    docbody.append(pagebreak(type='section', orient='portrait'))
    if noimagecopy:
        relationships, picpara, imagefiledict = picture(
            relationships,
            IMAGE1_FILE,
            'This is a test description',
            imagefiledict=imagefiledict)
    else:
        relationships, picpara = picture(relationships, IMAGE1_FILE,
                                         'This is a test description')
    docbody.append(picpara)
    docbody.append(pagebreak(type='section', orient='landscape'))
    docbody.append(paragraph('Paragraph 3'))
    if noimagecopy:
        return (document, docbody, relationships, imagefiledict)
    else:
        return (document, docbody, relationships)
コード例 #2
0
def testunsupportedpagebreak():
    """Ensure unsupported page break types are trapped"""
    document = newdocument()
    docbody = document.xpath('/w:document/w:body', namespaces=nsprefixes)[0]
    try:
        docbody.append(pagebreak(type='unsup'))
    except ValueError:
        return  # passed
    assert False  # failed
コード例 #3
0
ファイル: test_docx.py プロジェクト: bighome/python-docx-1
def testunsupportedpagebreak():
    """Ensure unsupported page break types are trapped"""
    document = newdocument()
    docbody = document.xpath("/w:document/w:body", namespaces=nsprefixes)[0]
    try:
        docbody.append(pagebreak(type="unsup"))
    except ValueError:
        return  # passed
    assert False  # failed
コード例 #4
0
    def __init__(self):
        # Default set of relationshipships - the minimum components of a document
        self.relationships = docx.relationshiplist()
    
        # Make a new document tree - this is the main part of a Word document
        self.document = docx.newdocument()

        # This xpath location is where most interesting content lives
        self.body = self.document.xpath('/w:document/w:body', namespaces=docx.nsprefixes)[0]

        self.create_header()
コード例 #5
0
    def __init__(self,
                 filename,
                 title='',
                 subject='',
                 creator='',
                 keywords=[],
                 page_margins={
                     'top': 2,
                     'bottom': 2,
                     'left': 3,
                     'right': 2
                 }):

        self.template_dir = os.path.join(
            os.path.dirname(filename),
            "docx_template_" + os.path.splitext(os.path.basename(filename))[0])
        if os.path.isdir(self.template_dir):
            shutil.rmtree(self.template_dir)
        shutil.copytree(
            os.path.join(os.path.dirname(__file__.replace("library.zip", '')),
                         'docx-template_clean'), self.template_dir)
        docx.template_dir = self.template_dir

        self.filename = filename
        self.title = title
        self.subject = subject
        self.creator = creator
        self.keywords = keywords

        # Default set of relationshipships - the minimum components of a document
        self.relationships = docx.relationshiplist()
        self.imagefiledict = {}

        # Make a new document tree - this is the main part of a Word document
        self.document = docx.newdocument(page_margins=page_margins)

        # This xpath location is where most interesting content lives
        self.body = self.document.xpath('/w:document/w:body',
                                        namespaces=docx.nsprefixes)[0]
        self.h = self.h1 = self.append_heading
        self.h2 = lambda s: self.append_heading(s, 2)
        self.h3 = lambda s: self.append_heading(s, 3)
        self.p = self.append_paragraph
        self.n = lambda s: self.append_paragraph([(s, 'ns')])
        self.i = lambda s: self.append_paragraph([(s, 'i')])
        self.b = lambda s: self.append_paragraph([(s, 'b')])
        self.new_page = lambda: self.body.append(pagebreak())
        self.table = docx.table
        self.paragraph = docx.paragraph
        self.caption = docx.caption
        self.heading = docx.heading
コード例 #6
0
    def __init__(self, builder):
        writers.Writer.__init__(self)
        self.builder = builder
        self.template_setup() # setup before call almost docx methods.

        dc = DocxContaner()
        dc.document = docx.newdocument()
        dc.docbody = dc.document.xpath(
                '/w:document/w:body', namespaces=docx.nsprefixes)[0]
        dc.relationships = docx.relationshiplist()
        dc.appprops = docx.appproperties()
        dc.contenttypes = docx.contenttypes()
        dc.websettings = docx.websettings()
        self.docx_container = dc
コード例 #7
0
ファイル: mw-glossary.py プロジェクト: berrueta/mw-glossary
def output_docx_glossary(glos, docxfilename):
    import docx # requires https://github.com/mikemaccana/python-docx
    items = glos.items()
    items.sort()
    relationships = docx.relationshiplist()
    document = docx.newdocument()
    docbody = document.xpath('/w:document/w:body', namespaces=docx.nsprefixes)[0]
    docbody.append(docx.heading("ONTORULE glossary", 1))
    for k,v in items:
        docbody.append(docx.heading(k, 2))
        docbody.append(docx.paragraph(to_docx(v)))
    coreprops = docx.coreproperties(title='ONTORULE glossary', subject="", creator='ONTORULE', keywords=[])
    appprops = docx.appproperties()
    contenttypes = docx.contenttypes()
    websettings = docx.websettings()
    wordrelationships = docx.wordrelationships(relationships)
    docx.savedocx(document,coreprops,appprops,contenttypes,websettings,wordrelationships, docxfilename)
コード例 #8
0
ファイル: docx_document.py プロジェクト: luasdtu/MMPE
    def __init__(self, filename, title='', subject='', creator='', keywords=[], page_margins={'top':2, 'bottom':2, 'left':3, 'right':2}):

        self.template_dir = os.path.join(os.path.dirname(filename), "docx_template_" + os.path.splitext(os.path.basename(filename))[0])
        if os.path.isdir(self.template_dir):
            shutil.rmtree(self.template_dir)
        shutil.copytree(os.path.join(os.path.dirname(__file__.replace("library.zip", '')), 'docx-template_clean'), self.template_dir)
        docx.template_dir = self.template_dir

        self.filename = filename
        self.title = title
        self.subject = subject
        self.creator = creator
        self.keywords = keywords

        # Default set of relationshipships - the minimum components of a document
        self.relationships = docx.relationshiplist()
        self.imagefiledict = {}


        # Make a new document tree - this is the main part of a Word document
        self.document = docx.newdocument(page_margins=page_margins)

        # This xpath location is where most interesting content lives
        self.body = self.document.xpath('/w:document/w:body', namespaces=docx.nsprefixes)[0]
        self.h = self.h1 = self.append_heading
        self.h2 = lambda s : self.append_heading(s, 2)
        self.h3 = lambda s : self.append_heading(s, 3)
        self.p = self.append_paragraph
        self.n = lambda s : self.append_paragraph([(s, 'ns')])
        self.i = lambda s : self.append_paragraph([(s, 'i')])
        self.b = lambda s : self.append_paragraph([(s, 'b')])
        self.new_page = lambda : self.body.append(pagebreak())
        self.table = docx.table
        self.paragraph = docx.paragraph
        self.caption = docx.caption
        self.heading = docx.heading
コード例 #9
0
 
    # Draw a basic graph image 
    for i in range(n):
        for j in range(i,n):
            if (A[i][j]==1):
                A[j][i]=1 # if edge exists => add backward mark in A matrix
                r+=1 # increase number of edges
                graph.add_edge(node[i],node[j]) # add an adge for drawing
    graph.layout(yapgvb.engines.dot) # 'Dot' fits the best
    format = yapgvb.formats.png
    filename = 'graph.%s' % format
    print "  Rendering %s ..." % filename
    graph.render(filename) # Draws a graph

    relationships = docx.relationshiplist()
    document = docx.newdocument()
    docbody = document.xpath('/w:document/w:body', namespaces=docx.nsprefixes)[0]
   
    docbody.append(heading(u'''6. Найти инварианты графа, заданного матрицей смежности ''',1)  )   
    
    # Create and insert basic table containing input info
    Table_Basic=[]
    for i in range(n+1):
        Table_Basic.append([])
        for j in range(n+1):
            Table_Basic[i].append("")
    for i in range(1,n+1):
        Table_Basic[0][i] = "x"+str(i)
        Table_Basic[i][0] = "x"+str(i)
    for i in range(1,n+1):
        for j in range(1, n+1):
コード例 #10
0
ファイル: views.py プロジェクト: danieltex/bugben
def generate_docx_resume():
    relationships = docx.relationshiplist()
    document = docx.newdocument()
    body = document.xpath('/w:document/w:body', namespaces=docx.nsprefixes)[0]
    data = resume_dict()

    body.append(docx.heading('Resume of', 3))
    body.append(docx.heading(data['resume'].name, 1))
    body.append(docx.heading(data['resume'].email, 2))
    body.append(docx.heading(data['resume'].url, 2))

    body.append(docx.heading('PROFILE SUMMARY', 2))
    for entry in data['profile_entries']:
        body.append(docx.paragraph(entry.entry, style='ListBullet'))

    body.append(docx.heading('LINKS', 2))
    for link in data['important_links']:
        body.append(docx.paragraph('%s - %s' % (
            link.description,
            link.url,
        ), style='ListBullet'))

    body.append(docx.heading('EXPERTISE', 2))
    for entry in data['expertise_entries']:
        body.append(docx.paragraph(entry.entry, style='ListBullet'))


    # experience
    ret += 'EXPERIENCE'.ljust(text_width, '.') + '\n'
    ret += '\n'
    for entry in data['work_history_entries']:
        ret += '   ' + entry.client_name.upper() + '\n'
        ret += '   ' + entry.location + '\n'
        ret += '   ' + entry.timespan + '\n'
        ret += '   ' + entry.title + '\n'
        ret += '\n'
        for achievement in entry.workachievement_set.all():
            wrapped = textwrap.fill(
                achievement.description,
                text_width-6,
                subsequent_indent='      ',
            )
            ret += '      ' + wrapped + '\n'
            ret += '\n'
        ret += '\n\n'

    # contributions
    ret += 'COMMUNITY CONTRIBUTIONS'.ljust(text_width, '.') + '\n'
    ret += '\n'
    for project in data['projects']:
        ret += '   ' + project.name.upper() + '\n'
        wrapped = textwrap.fill(
            strip_tags(project.short_description),
            text_width-3,
            subsequent_indent='   ',
        )
        ret += '   ' + wrapped + '\n'
        wrapped = textwrap.fill(
            strip_tags(project.long_description),
            text_width-3,
            subsequent_indent='   ',
        )
        ret += '   ' + wrapped + '\n\n'
        if project.deployment_url:
            ret += '      Project Page: %s\n' % project.deployment_url
            ret += '      Source Code:  %s\n' % project.src_url
        ret += '\n\n'

    tag_line_top = "This is my plain text resume generator"
    tag_line_middle = "Outputting at %s columns" % text_width
    tag_line_bottom = "http://github.com/ben174/bugben"

    ret += '-' * text_width + '\n'
    ret += tag_line_top.center(text_width) + '\n'
    ret += tag_line_middle.center(text_width) + '\n'
    ret += tag_line_bottom.center(text_width) + '\n'
    ret += '-' * text_width + '\n'



    # Create our properties, contenttypes, and other support files
    title    = 'Resume of %s' % data['resume'].name
    subject  = 'My awesome resume!'
    creator  =  data['resume'].name
    keywords = []

    coreprops = docx.coreproperties(
        title=title,
        subject=subject,
        creator=creator,
        keywords=keywords,
    )
    appprops = docx.appproperties()
    contenttypes = docx.contenttypes()
    websettings = docx.websettings()
    wordrelationships = docx.wordrelationships(relationships)


    data = None
    with tempfile.NamedTemporaryFile() as temp:
        docx.savedocx(
            document,
            coreprops,
            appprops,
            contenttypes,
            websettings,
            wordrelationships,
            temp.name
        )
        data = open(temp.name).read()
    return data
コード例 #11
0
ファイル: utils.py プロジェクト: elisiano/cern-tender
def get_document_docx(filename, doc_id, start_index=1):
    """filename is a file like object (like an HttpResponse)"""
    
    doc = get_doc_copy_with_references(doc_id, start_index=1)
    
    H1 = partial(docx.heading,headinglevel=1)
    H2 = partial(docx.heading,headinglevel=2)
    N = partial(docx.paragraph,style='')
    
    ### Followed the example of the author of the library
    relationships = docx.relationshiplist()
    document = docx.newdocument()
    docbody = document.xpath('/w:document/w:body', namespaces=docx.nsprefixes)[0]

    docbody.append(docx.paragraph([('CERN - European Organisation for Nuclear Research','b')],jc='center'))
    docbody.append(docx.paragraph([('1211 Geneva 23, Switzerland', 'b')],jc='center'))


    ### Unable to center the table, commending it for no
#    docbody.append(docx.table(
#                            [[docx.paragraph([('Invitation to tender %s' % doc_id,'b')],jc='center')]], 
#                            heading=False,
#                            borders={'all':{'color':'auto', 'size':'1', 'val':'single'}},
#                                
#                            ))

    story = docbody
    story.append(N(''))
    story.append(N(''))
    story.append(docx.paragraph([('Invitation to tender %s' % doc_id,'bu')],jc='center'))
    story.append(N(''))
    story.append(docx.paragraph([('Technical Specifications','bi')],jc='center'))
    story.append(N(''))

    
    if doc.get('intro', None):
        story.append(H1(doc['intro_header'] or 'Scope of the invitaion to Tender'))
        story.append(N(doc['intro']))
        
    for sys in range(len(doc.get('systems',[]))):
        system = doc['systems'][sys]
        bt = "%d" % (start_index + sys)
        story.append(N('\n\n'))
        story.append(H1('%s. %s' % (bt, system['name'])))

        if system['description']:
            story.append(N(system['description']))

        for sec in range(len(system.get('sections',[]))):

            section=system['sections'][sec]
            bt = '%d.%d' % (start_index + sys, sec+1)

            story.append(
                        H2('%s. %s' % (bt, section['header']))
                    )

            if section['description']:
                story.append(N(section['description']))

            for q in range(len(section.get('questions',[]))):
                question = section['questions'][q]
                bt = "%d.%d.%d" % (start_index + sys, sec+1, q+1)

                story.append(N('\t%s. %s' % (bt, question['tech_spec'])))


    if doc.get('contacts', None):
        contacts_per_row=3
        _cs = copy.deepcopy(doc.get('contacts',[]))
        table_data = []
        # let's pad the table
        while len(_cs) % contacts_per_row != 0:
            _cs.append(dict({u'type_':'', u'name':'', u'address':'',u'tel':'',u'fax':'', u'email':''}))
        stack = []
        for ci in range(len(_cs)):
            stack.append(_cs[ci])
            if len(stack) == contacts_per_row:
                table_data.append([ u'']       + [c['type_']+':' if c['type_'] else '' for c in stack])
                table_data.append([u'Name']    + [c['name'] for c in stack])
                table_data.append([u'Address'] + [c['address'].replace('\r','') for c in stack])
                table_data.append([u'Tel']     + [c['tel'] for c in stack])
                table_data.append([u'Fax']     + [c['fax'] for c in stack])
                table_data.append([u'E-mail']  + [c['email'] for c in stack])
                table_data.append([u'']*(contacts_per_row+1))
                stack=[]

        story.append(docx.pagebreak())
        story.append(H1('Contacts'))
        story.append(docx.table(table_data, heading=False))

    # Create our properties, contenttypes, and other support files
    coreprops = docx.coreproperties(title='Invitation to tender %s' % doc_id,subject='IT %s Technical Specifications',creator='Elisiano Petrini',keywords=['tender','Office Open XML','Word','%s' % doc_id])
    appprops = docx.appproperties()
    contenttypes = docx.contenttypes()
    websettings = docx.websettings()
    wordrelationships = docx.wordrelationships(relationships)
    f = tempfile.NamedTemporaryFile(delete=False)
    docx.savedocx(document,coreprops,appprops,contenttypes,websettings,wordrelationships, f.name)
    f.close()
    with open(f.name, 'rb') as f:
        filename.write(f.read())
    os.unlink(f.name)
    return document
コード例 #12
0
If you need to make documents from scratch, use this file as a basis for your work.

Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
'''
import shutil
from copy import deepcopy
from tempfile import TemporaryFile, mkdtemp
import docx as dx

if __name__ == '__main__':
    # Default set of relationshipships - these are the minimum components of a document
    relationships = dx.getRelationships()

    # Make a new document tree - this is the main part of a Word document
    document = dx.newdocument()

    # This xpath location is where most interesting content lives
    docbody = document.xpath('/w:document/w:body', namespaces=dx.nsprefixes)[0]

    # Append two headings and a paragraph
    docbody.append(dx.heading('''Welcome to Python's docx module''', 1))
    docbody.append(
        dx.heading('Make and edit docx in 200 lines of pure Python', 2))
    docbody.append(
        dx.paragraph(
            'The module was created when I was looking for a Python support for MS Word .doc files on PyPI and Stackoverflow. Unfortunately, the only solutions I could find used:'
        ))

    # Add a numbered list
    for point in [
コード例 #13
0
If you need to make documents from scratch, use this file as a basis for your work.

Part of Python's docx module - http://github.com/mikemaccana/python-docx
See LICENSE for licensing information.
'''
import shutil
from copy import deepcopy
from tempfile import TemporaryFile, mkdtemp
import docx as dx

if __name__ == '__main__':
    # Default set of relationshipships - these are the minimum components of a document
    relationships = dx.getRelationships()

    # Make a new document tree - this is the main part of a Word document
    document = dx.newdocument()
    
    # This xpath location is where most interesting content lives 
    docbody = document.xpath('/w:document/w:body', namespaces=dx.nsprefixes)[0]

    # Append two headings and a paragraph
    docbody.append(dx.heading('''Welcome to Python's docx module''',1)  )   
    docbody.append(dx.heading('Make and edit docx in 200 lines of pure Python',2))
    docbody.append(dx.paragraph('The module was created when I was looking for a Python support for MS Word .doc files on PyPI and Stackoverflow. Unfortunately, the only solutions I could find used:'))

    # Add a numbered list
    for point in ['''COM automation''','''.net or Java''','''Automating OpenOffice or MS Office''']:
        docbody.append(dx.paragraph(point,style='ListNumber'))
    docbody.append(dx.paragraph('''For those of us who prefer something simpler, I made docx.''')) 
    
    docbody.append(dx.heading('Making documents',2))
コード例 #14
0
        add_hyperlink(p, doralinkprefix + row[pidkey])
    run = docx.makeelement('r')
    rPr = docx.makeelement('rPr')
    run.append(rPr)
    t = docx.makeelement('t', tagtext=" ")
    t.set('{http://www.w3.org/XML/1998/namespace}space', 'preserve')
    run.append(t)
    p.append(run)
    add_hyperlink(p, (refworksreportlinkprefix if
                      (refid and refid < 10000) else refworkslinkprefix) +
                  row["ID"])
    doc_body.append(p)
    return p


doc = docx.newdocument()
doc_body = None
for el in doc.iter():
    if el.tag == '{' + docx.nsprefixes['w'] + '}body':
        doc_body = el
        break
doc_body.append(docx.heading(title + " (" + str(len(outvals)) + ")", 1))
doc_body.append(
    docx.paragraph([
        "This report contains all publication types except for \"" +
        (excludegenres[0] if len(excludegenres) <= 1 else "\"; \"".join(
            [excludegenres[k] for k in range(len(excludegenres) - 1)]) +
         "\" and \"" + excludegenres[len(excludegenres) - 1]) + "\"" +
        (", as well as publications published before " +
         str(yearmin) if yearmin else "") + ".", ''
    ]))
コード例 #15
-1
ファイル: test_docx.py プロジェクト: bighome/python-docx-1
def simpledoc(noimagecopy=False):
    """Make a docx (document, relationships) for use in other docx tests"""
    relationships = relationshiplist()
    imagefiledict = {}
    document = newdocument()
    docbody = document.xpath("/w:document/w:body", namespaces=nsprefixes)[0]
    docbody.append(heading("Heading 1", 1))
    docbody.append(heading("Heading 2", 2))
    docbody.append(paragraph("Paragraph 1"))
    for point in ["List Item 1", "List Item 2", "List Item 3"]:
        docbody.append(paragraph(point, style="ListNumber"))
    docbody.append(pagebreak(type="page"))
    docbody.append(paragraph("Paragraph 2"))
    docbody.append(table([["A1", "A2", "A3"], ["B1", "B2", "B3"], ["C1", "C2", "C3"]]))
    docbody.append(pagebreak(type="section", orient="portrait"))
    if noimagecopy:
        relationships, picpara, imagefiledict = picture(
            relationships, IMAGE1_FILE, "This is a test description", imagefiledict=imagefiledict
        )
    else:
        relationships, picpara = picture(relationships, IMAGE1_FILE, "This is a test description")
    docbody.append(picpara)
    docbody.append(pagebreak(type="section", orient="landscape"))
    docbody.append(paragraph("Paragraph 3"))
    if noimagecopy:
        return (document, docbody, relationships, imagefiledict)
    else:
        return (document, docbody, relationships)