Beispiel #1
0
def testnewdocument():
    """Test that a new document can be created"""
    document, docbody, relationships = simpledoc()
    coreprops = coreproperties('Python docx testnewdocument',
                               'A short example of making docx from Python',
                               'Alan Brooks',
                               ['python', 'Office Open XML', 'Word'])
    savedocx(document, coreprops, appproperties(), contenttypes(),
             websettings(), wordrelationships(relationships), TEST_FILE)
Beispiel #2
0
    def save(self, filename):
        dc = self.docx_container
        wordrelationships = docx.wordrelationships(dc.relationships)
        coreprops = docx.coreproperties(
                title='Python docx demo',
                subject='A practical example of making docx from Python',
                creator='Mike MacCana',
                keywords=['python', 'Office Open XML', 'Word'])

        docx.savedocx(dc.document, coreprops, dc.appprops, dc.contenttypes,
                dc.websettings, wordrelationships, filename)
Beispiel #3
0
def testnewdocument():
    """Test that a new document can be created"""
    document, docbody, relationships = simpledoc()
    coreprops = coreproperties(
        "Python docx testnewdocument",
        "A short example of making docx from Python",
        "Alan Brooks",
        ["python", "Office Open XML", "Word"],
    )
    savedocx(
        document, coreprops, appproperties(), contenttypes(), websettings(), wordrelationships(relationships), TEST_FILE
    )
Beispiel #4
0
    def save(self, filename=None):
        if filename is not None:
            self.filename = filename

        coreprops = docx.coreproperties(title=self.title,
                                        subject=self.subject,
                                        creator=self.creator,
                                        keywords=self.keywords)
        appprops = docx.appproperties()
        contenttypes = docx.contenttypes()
        websettings = docx.websettings()
        wordrelationships = docx.wordrelationships(self.relationships)
        # Save our document
        docx.savedocx(self.document, coreprops, appprops, contenttypes,
                      websettings, wordrelationships, self.filename)
Beispiel #5
0
    def save(self, filename=None):
        if filename is not None:
            self.filename = filename

        coreprops = docx.coreproperties(title=self.title,
                                   subject=self.subject,
                                   creator=self.creator,
                                   keywords=self.keywords)
        appprops = docx.appproperties()
        contenttypes = docx.contenttypes()
        websettings = docx.websettings()
        wordrelationships = docx.wordrelationships(self.relationships)
        # Save our document
        docx.savedocx(self.document, coreprops, appprops, contenttypes, websettings,
                 wordrelationships, self.filename)
Beispiel #6
0
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)
    def save(self, filename):
        """
        Save the document
        """
        # Create our properties, contenttypes, and other support files
        title = 'CuroSeven custom report'
        subject = 'A practical example of making docx from Python'
        creator = 'CuroSeven'
        keywords = ['CuroSeven']

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

        docx.savedocx(self.document, coreprops, appprops, contenttypes, websettings,
             wordrelationships, filename)
    else: print 'nope.'
    
    print 'Searching for something in a heading ...',
    if search(docbody, '200 lines'): print 'found it!'
    else: print 'nope.'
    
    print 'Replacing ...',
    docbody = replace(docbody,'the awesomeness','the goshdarned awesomeness') 
    print 'done.'

    # Add a pagebreak
    docbody.append(pagebreak(type='page', orient='portrait'))

    docbody.append(heading('Ideas? Questions? Want to contribute?',2))
    docbody.append(paragraph('''Email <*****@*****.**>'''))
    """

    # Create our properties, contenttypes, and other support files
    coreprops = docx.coreproperties(title=u'Контрольная работа',subject=u'ОДМиТА, Задание №6',creator='*****@*****.**',keywords=['БГУИР',u'ОДМиТА','python'])
    appprops = docx.appproperties()
    contenttypes = docx.contenttypes()
    websettings = docx.websettings()
    wordrelationships = docx.wordrelationships(relationships)
    
    # Save our document
    docx.savedocx(document,coreprops,appprops,contenttypes,websettings,wordrelationships,'./output/solution.docx')
    # Remove temporary image files
    os.remove('graph.png')
    
    
    
Beispiel #9
0
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
Beispiel #10
0
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
    print 'Searching for something in a heading ...',
    if dx.search(docbody, '200 lines'):
        print 'found it!'
    else:
        print 'nope.'

    print 'Replacing ...',
    docbody = dx.replace(docbody, 'the awesomeness',
                         'the goshdarned awesomeness')
    print 'done.'

    # Add a pagebreak
    docbody.append(dx.pagebreak(type='page', orient='portrait'))

    docbody.append(dx.heading('Ideas? Questions? Want to contribute?', 2))
    docbody.append(dx.paragraph('''Email <*****@*****.**>'''))

    # Create our properties, contenttypes, and other support files
    coreprops = dx.coreproperties(
        title='Python docx demo',
        subject='A practical example of making docx from Python',
        creator='Mike MacCana',
        keywords=['python', 'Office Open XML', 'Word'])
    appprops = dx.appproperties()
    my_contenttypes = dx.getContentTypes()
    my_websettings = dx.websettings()

    # Save our document
    dx.savedocx(document, coreprops, appprops, my_contenttypes, my_websettings,
                relationships, 'Welcome to the Python docx module.docx')
         print 'nope.'
         
    print 'Searching for something in a heading ...',
    if dx.search(docbody, '200 lines'):
         print 'found it!'
    else:
         print 'nope.'
    
    print 'Replacing ...',
    docbody = dx.replace(docbody,'the awesomeness','the goshdarned awesomeness') 
    print 'done.'

    # Add a pagebreak
    docbody.append(dx.pagebreak(type='page', orient='portrait'))

    docbody.append(dx.heading('Ideas? Questions? Want to contribute?',2))
    docbody.append(dx.paragraph('''Email <*****@*****.**>'''))

    # Create our properties, contenttypes, and other support files
    coreprops = dx.coreproperties(
        title='Python docx demo',
        subject='A practical example of making docx from Python',
        creator='Mike MacCana',
        keywords=['python','Office Open XML','Word'])
    appprops = dx.appproperties()
    my_contenttypes = dx.getContentTypes()
    my_websettings = dx.websettings()
    
    # Save our document
    dx.savedocx(document,coreprops,appprops,my_contenttypes,my_websettings,relationships,'Welcome to the Python docx module.docx')
Beispiel #13
0
    <h1>PDF Demo</h1>
    <p>lala</p>
    <h2>h2</h2>
  </body>
</html>
"""
result = StringIO.StringIO()
pdf = pisa.CreatePDF(StringIO.StringIO(html), result)
f = open('generated.pdf', 'w')
f.write(result.getvalue())

import odf.opendocument
import odf.text
textdoc = odf.opendocument.OpenDocumentText()
p = odf.text.P(text="Hello World!")
textdoc.text.addElement(p)
textdoc.save("generated", True)

import docx
document = docx.newdocument()
docbody = document.xpath('/w:document/w:body', namespaces=docx.nsprefixes)[0]
docbody.append(docx.heading('''Welcome to Python's docx module''',1)  )   
docbody.append(docx.heading('Make and edit docx in 200 lines of pure Python',2))
docbody.append(docx.paragraph('The module was created when I was looking for a Python support for MS Word .doc files'))
coreprops = docx.coreproperties(title='Python docx demo',subject='A practical example of making docx from Python',creator='stas',keywords=['python','Office Open XML','Word'])
appprops = docx.appproperties()
contenttypes = docx.contenttypes()
websettings = docx.websettings()
wordrelationships = docx.wordrelationships(docx.relationshiplist())
docx.savedocx(document, coreprops, appprops, contenttypes, websettings, wordrelationships, 'generated.docx')
    makeref(doc_body, outvals[n])
doc_body.append(
    docx.heading(
        " / ".join(articlegenres) + u" \u2013 " + nrkey + " (" +
        str(len(allnrarts)) + ")", 2))
for n in allnrarts:
    makeref(doc_body, outvals[n])
doc_body.append(
    docx.heading(" / ".join(othergenres) + " (" + str(len(alloths)) + ")", 2))
for n in alloths:
    makeref(doc_body, outvals[n])
doc_rels = docx.wordrelationships(docx.relationshiplist() +
                                  makehyperlinkrelationshiplist())
doc_rels = correctrelationships(doc_rels)
docx.savedocx(doc, docx.coreproperties(title, "", "prepare_reports.py", ""),
              docx.appproperties(), docx.contenttypes(), docx.websettings(),
              doc_rels, statoutfiles[allkey])

for key in orgunits:
    if verbose:
        print "Exporting to " + outfiles[key] + "..."

    with codecs.open(outfiles[key], "wb", "utf8") as outfd:
        csvwriter = UnicodeDictWriter(outfd,
                                      outheader,
                                      delimiter="\t",
                                      quoting=csv.QUOTE_NONE,
                                      quotechar='',
                                      escapechar='\\')
        csvwriter.writeheader()
        rarts = ouarticles[key][rkey] if key in ouarticles else []