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)
def append_table( self, lst_of_lst, heading=True, colw=None, cwunit='dxa', tblw=0, twunit='auto', borders={"all": { "color": 'auto', 'val': 'single', 'sz': '4' }}, column_style={ 'all': { 'font_size': 10, 'spacing': { 'before': 0, 'after': 0 } } }): """ @param list contents: A list of lists describing contents. Every item in the list can be a string or a valid XML element itself. It can also be a list. In that case all the listed elements will be merged into the cell. @param bool heading: Tells whether first line should be treated as heading or not @param list colw: list of integer column widths specified in wunitS. @param str cwunit: Unit used for column width: 'pct' : fiftieths of a percent 'dxa' : twentieths of a point 'nil' : no width 'auto' : automagically determined @param int tblw: Table width @param str twunit: Unit used for table width. Same possible values as cwunit. @param dict borders: Dictionary defining table border. Supported keys are: 'top', 'left', 'bottom', 'right', 'insideH', 'insideV', 'all'. When specified, the 'all' key has precedence over others. Each key must define a dict of border attributes: color : The color of the border, in hex or 'auto' space : The space, measured in points sz : The size of the border, in eighths of a point val : The style of the border, see http://www.schemacentral.com/sc/ooxml/t-w_ST_Border.htm @param list celstyle: Specify the style for each colum, list of dicts. supported keys: 'align' : specify the alignment, see paragraph documentation.""" self.body.append( table(lst_of_lst, heading, colw, cwunit, tblw, twunit, borders, column_style))
def testtable(): """Ensure tables make sense""" testtable = table([['A1', 'A2'], ['B1', 'B2'], ['C1', 'C2']]) assert (testtable.xpath('/ns0:tbl/ns0:tr[2]/ns0:tc[2]/ns0:p/ns0:r/ns0:t', namespaces={ 'ns0': ('http://schemas.openxmlformats.org/wordproce' 'ssingml/2006/main') })[0].text == 'B2')
def testtable(): """Ensure tables make sense""" testtable = table([["A1", "A2"], ["B1", "B2"], ["C1", "C2"]]) assert ( testtable.xpath( "/ns0:tbl/ns0:tr[2]/ns0:tc[2]/ns0:p/ns0:r/ns0:t", namespaces={"ns0": ("http://schemas.openxmlformats.org/wordproce" "ssingml/2006/main")}, )[0].text == "B2" )
def depart_table(self, node): dprint() lines = self.table[1:] fmted_rows = [] # don't allow paragraphs in table cells for now for line in lines: if line == 'sep': pass else: fmted_rows.append(line) self.docbody.append(docx.table(fmted_rows)) self.table = None self.end_state()
def append_table(self, lst_of_lst, heading=True, colw=None, cwunit='dxa', tblw=0, twunit='auto', borders={"all":{"color":'auto', 'val':'single', 'sz':'4'}}, column_style={'all':{'font_size':10, 'spacing':{'before':0, 'after':0}}}): """ @param list contents: A list of lists describing contents. Every item in the list can be a string or a valid XML element itself. It can also be a list. In that case all the listed elements will be merged into the cell. @param bool heading: Tells whether first line should be treated as heading or not @param list colw: list of integer column widths specified in wunitS. @param str cwunit: Unit used for column width: 'pct' : fiftieths of a percent 'dxa' : twentieths of a point 'nil' : no width 'auto' : automagically determined @param int tblw: Table width @param str twunit: Unit used for table width. Same possible values as cwunit. @param dict borders: Dictionary defining table border. Supported keys are: 'top', 'left', 'bottom', 'right', 'insideH', 'insideV', 'all'. When specified, the 'all' key has precedence over others. Each key must define a dict of border attributes: color : The color of the border, in hex or 'auto' space : The space, measured in points sz : The size of the border, in eighths of a point val : The style of the border, see http://www.schemacentral.com/sc/ooxml/t-w_ST_Border.htm @param list celstyle: Specify the style for each colum, list of dicts. supported keys: 'align' : specify the alignment, see paragraph documentation.""" self.body.append(table(lst_of_lst, heading, colw, cwunit, tblw, twunit, borders, column_style))
def replaceTag(doc, tag, replace, fmt = {}): """ Searches for {{tag}} and replaces it with replace. Replace is a list with two indexes: 0=type, 1=The replacement Supported values for type: 'str': <string> Renders a simple text string 'tab': <list> Renders a table, use fmt to tune look """ if replace[0] == 'str': repl = unicode(replace[1]) elif replace[0] == 'tab': # Will make a table r = [] for el in replace[1]: # Unicodize r.append( map(lambda i: unicode(i), el) ) if not len(r): # Empty table repl = '' else: repl = docx.table( r, heading = fmt['heading'] if 'heading' in fmt.keys() else False, colw = fmt['colw'] if 'colw' in fmt.keys() else None, cwunit = fmt['cwunit'] if 'cwunit' in fmt.keys() else 'dxa', tblw = fmt['tblw'] if 'tblw' in fmt.keys() else 0, twunit = fmt['twunit'] if 'twunit' in fmt.keys() else 'auto', borders = fmt['borders'] if 'borders' in fmt.keys() else {}, celstyle = fmt['celstyle'] if 'celstyle' in fmt.keys() else None, headstyle = fmt['headstyle'] if 'headstyle' in fmt.keys() else {}, ) else: raise NotImplementedError, "Unsupported " + replace[0] + " tag type!" return docx.advReplace(doc, '\{\{'+re.escape(tag)+'\}\}', repl)
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): Table_Basic[i][j]=str(A[i-1][j-1]) docbody.append(table(Table_Basic,False,borders={'all':{'color':'auto','space':1,'sz':1}})) docbody.append(heading(u'Решение:',2)) docbody.append(paragraph(u'Согласно отношениям смежности, изобразим граф:')) # Insert an image of graph relationships,picpara = picture(relationships,'graph.png','',200,200) docbody.append(picpara) docbody.append(heading(u'1. Количество вершин n = %i'%(n),2)) docbody.append(heading(u'2. Количество ребер r = %i'%(r),2)) f = 2-n+r docbody.append(heading(u'3. Количество граней f = %i'%(f),2)) docbody.append(paragraph('n-r+f = 2'))
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
docbody.append( dx.paragraph('''The docx module has the following features:''', font='Arial', fontsize=10)) # Add some bullets for point in [ 'Paragraphs', 'Bullets', 'Numbered lists', 'Multiple levels of headings', 'Tables', 'Document Properties' ]: docbody.append(dx.paragraph(point, style='ListBullet')) docbody.append(dx.paragraph('Tables are just lists of lists, like this:')) # Append a table docbody.append( dx.table([['A1', 'A2', 'A3'], ['B1', 'B2', 'B3'], ['C1', 'C2', 'C3']])) docbody.append(dx.heading('Editing documents', 2)) docbody.append( dx.paragraph('Thanks to the awesomeness of the lxml module, we can:')) for point in [ 'Search and replace', 'Extract plain text of document', 'Add and delete items anywhere within the document' ]: docbody.append(dx.paragraph(point, style='ListBullet')) # Add an image relationships, picpara = dx.picture(relationships, 'image1.png', 'This is a test description') docbody.append(picpara)
# 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)) docbody.append(dx.paragraph('''The docx module has the following features:''', font='Arial', fontsize=10)) # Add some bullets for point in ['Paragraphs','Bullets','Numbered lists','Multiple levels of headings','Tables','Document Properties']: docbody.append(dx.paragraph(point,style='ListBullet')) docbody.append(dx.paragraph('Tables are just lists of lists, like this:')) # Append a table docbody.append(dx.table([['A1','A2','A3'],['B1','B2','B3'],['C1','C2','C3']])) docbody.append(dx.heading('Editing documents',2)) docbody.append(dx.paragraph('Thanks to the awesomeness of the lxml module, we can:')) for point in ['Search and replace', 'Extract plain text of document', 'Add and delete items anywhere within the document']: docbody.append(dx.paragraph(point, style='ListBullet')) # Add an image relationships, picpara = dx.picture( relationships, 'image1.png', 'This is a test description') docbody.append(picpara)
n_oths = len(ouothers[key] if key in ouothers else []) n_tot = n_rarts + n_nrarts + n_oths stats_table.append( [key, str(n_rarts), str(n_nrarts), str(n_oths), str(n_tot)]) stats_table.append([ "TOTAL Eawag", str(len(allrarts)), str(len(allnrarts)), str(len(alloths)), str(len(outvals)) ]) doc_body.append( docx.table(stats_table, colw=[2000, 1700, 1700, 1700, 1700], cwunit='dxa')) doc_body.append( docx.paragraph([ "Note: Articles include the publication types \"" + "\", \"".join( [articlegenres[k] for k in range(len(articlegenres) - 1)]) + "\" and \"" + articlegenres[len(articlegenres) - 1] + "\", whereas Others include the publication types \"" + "\", \"".join([othergenres[k] for k in range(len(othergenres) - 1)]) + "\" and \"" + othergenres[len(othergenres) - 1] + "\".", '' ])) doc_body.append( docx.heading( " / ".join(articlegenres) + u" \u2013 " + rkey + " (" + str(len(allrarts)) + ")", 2)) for n in allrarts: makeref(doc_body, outvals[n])
# Add a numbered list for point in ['''COM automation''', '''.net or Java''', '''Automating OpenOffice or MS Office''']: docbody.append( docx.paragraph( point, style = 'ListNumber' ) ) docbody.append( docx.paragraph( '''For those of us who prefer something simpler, I made docx.''' ) ) docbody.append( docx.heading( 'Making documents', 2 ) ) docbody.append( docx.paragraph( '''The docx module has the following features:''' ) ) # Add some bullets for point in ['Paragraphs', 'Bullets', 'Numbered lists', 'Multiple levels of headings', 'Tables', 'Document Properties']: docbody.append( docx.paragraph( point, style = 'ListBullet' ) ) docbody.append( docx.paragraph( 'Tables are just lists of lists, like this:' ) ) # Append a table docbody.append( docx.table( [['A1', 'A2', 'A3'], ['B1', 'B2', 'B3'], ['C1', 'C2', 'C3']] ) ) docbody.append( docx.heading( 'Editing documents', 2 ) ) docbody.append( docx.paragraph( 'Thanks to the awesomeness of the lxml module, we can:' ) ) for point in ['Search and replace', 'Extract plain text of document', 'Add and delete items anywhere within the document']: docbody.append( docx.paragraph( point, style = 'ListBullet' ) ) # Add an image relationships, picpara = docx.picture( relationships, 'image1.png', 'This is a test description' ) docbody.append( picpara ) # Search and replace print 'Searching for something in a paragraph ...', if docx.search( docbody, 'the awesomeness' ): print 'found it!' else: print 'nope.'
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)