def GetStyles(self): # doc = Document() # 在脚本打包成二进制时,需要指定default.docx路径,否则会报错 doc = Document(docx=os.path.join(os.getcwd(), 'default.docx')) style_head = doc.styles.add_style('style_head', WD_STYLE_TYPE.PARAGRAPH) style_head.font.size = Pt(25) style_head.font.name = u'微软雅黑' style_head.font.bold = True style_head._element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑') style_head.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER style_title = doc.styles.add_style('style_title', WD_STYLE_TYPE.PARAGRAPH) style_title.font.size = Pt(15) style_title.font.name = u'微软雅黑' style_title.font.bold = True style_title._element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑') sub_title = doc.styles.add_style('sub_title', WD_STYLE_TYPE.PARAGRAPH) sub_title.font.size = Pt(10) sub_title.font.name = u'微软雅黑' sub_title.font.bold = True sub_title._element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑') return doc, style_head, style_title, sub_title
def highlight_run(run): hl = etree.Element(qn("w:highlight")) hl.set(qn("w:val"), "yellow") rpr = run._r.get_or_add_rPr() rpr.append(hl) # Highlighted text is underlined as well run.style = "Style Bold Underline"
def create_list(paragraph, list_type): p = paragraph._p #access to xml paragraph element pPr = p.get_or_add_pPr() #access paragraph properties numPr = OxmlElement('w:numPr') #create number properties element numId = OxmlElement('w:ilvl') #create numId element - sets bullet type numId.set(qn('w:val'), '1') #set list type/indentation numPr.append(numId) #add bullet type to number properties list numId = OxmlElement('w:numId') #create numId element - sets bullet type numId.set(qn('w:val'), str(list_type+1)) numPr.append(numId) #add bullet type to number properties list pPr.append(numPr) #add number properties to paragraph
def get_child_element(obj): child = obj.find(qn(self._nsptagname)) if child is None: raise InvalidXmlError( "required ``<%s>`` child element not present" % self._nsptagname ) return child
def remove_all(self, *tagnames): """ Remove all child elements whose tagname (e.g. 'a:p') appears in *tagnames*. """ for tagname in tagnames: matching = self.findall(qn(tagname)) for child in matching: self.remove(child)
def first_child_found_in(self, *tagnames): """ Return the first child found with tag in *tagnames*, or None if not found. """ for tagname in tagnames: child = self.find(qn(tagname)) if child is not None: return child return None
def it_removes_header_part(self): document = Document(dir_pkg_path) document.remove_headers() for rel_id, part in document.part.related_parts.items(): assert part.content_type != CT.WML_HEADER header_elm_tag = 'w:headerReference' sentinel_sectPr = document._body._body.get_or_add_sectPr() header_elms = sentinel_sectPr.findall(qn(header_elm_tag)) assert len(header_elms) == 0
def _set_element_datetime(self, prop_name, value): """ Set date/time value of child element having *prop_name* to *value*. """ if not isinstance(value, datetime): tmpl = ( "property requires <type 'datetime.datetime'> object, got %s" ) raise ValueError(tmpl % type(value)) element = self._get_or_add(prop_name) dt_str = value.strftime('%Y-%m-%dT%H:%M:%SZ') element.text = dt_str if prop_name in ('created', 'modified'): # These two require an explicit 'xsi:type="dcterms:W3CDTF"' # attribute. The first and last line are a hack required to add # the xsi namespace to the root element rather than each child # element in which it is referenced self.set(qn('xsi:foo'), 'bar') element.set(qn('xsi:type'), 'dcterms:W3CDTF') del self.attrib[qn('xsi:foo')]
def it_removes_footer_part(self): document = Document(dir_pkg_path) document.remove_footers() for rel_id, part in document.part.related_parts.items(): assert part.content_type != CT.WML_FOOTER footer_elm_tag = "w:footerReference" sentinel_sectPr = document._body._body.get_or_add_sectPr() footer_elms = sentinel_sectPr.findall(qn(footer_elm_tag)) assert len(footer_elms) == 0
def EditArticle(self, articleTime, articleTitle, articleContent): # Article style setting self.document.styles["Normal"].font.name = "宋体" self.r = self.document.styles["Normal"]._element self.r.rPr.rFonts.set(qn("w:eastAsia"), "宋体") self.document.styles["Normal"].font.size = Pt(10.5) # Editting article self.document.add_paragraph(articleTitle) self.document.add_paragraph(articleContent) # Saving document sys.stdout.write("|>Saving..." + self.documentTitle) self.document.save(self.documentTitle) sys.stdout.write(" Saved<|\n")
def it_adds_to_doc_without_header(self): document = Document(dir_pkg_path) header = document.add_header() header_elm_tag = 'w:headerReference' sentinel_sectPr = document._body._body.get_or_add_sectPr() header_elms = sentinel_sectPr.findall(qn(header_elm_tag)) assert len(header_elms) == 1 assert header assert len(header.paragraphs) == 0 header.add_paragraph('foobar') assert len(header.paragraphs) == 1
def set_cell_border(cell, **kwargs): """ Set cell`s border Usage: set_cell_border( cell, top={"sz": 0, "val": "single", "color": "#FF0000", "space": "0"}, bottom={"sz": 0, "color": "#00FF00", "val": "single"}, left={"sz": 24, "val": "dashed", "shadow": "true"}, right={"sz": 0, "val": "dashed"}, ) """ tc = cell._tc tcPr = tc.get_or_add_tcPr() # check for tag existnace, if none found, then create one tcBorders = tcPr.first_child_found_in("w:tcBorders") if tcBorders is None: tcBorders = OxmlElement('w:tcBorders') tcPr.append(tcBorders) # list over all available tags for edge in ('left', 'top', 'right', 'bottom', 'insideH', 'insideV'): edge_data = kwargs.get(edge) if edge_data: tag = 'w:{}'.format(edge) # check for tag existnace, if none found, then create one element = tcBorders.find(qn(tag)) if element is None: element = OxmlElement(tag) tcBorders.append(element) # looks like order of attributes is important for key in ["sz", "val", "color", "space", "shadow"]: if key in edge_data: element.set(qn('w:{}'.format(key)), str(edge_data[key]))
def add_border(cell: _Cell): ''' <w:tcPr> <w:tcBorders> <w:top w:val="double" w:sz="24" w:space="0" w:color="FF0000"> <w:start w:val="double" w:sz="24" w:space="0" w:color="FF0000"> <w:bottom w:val="double" w:sz="24" w:space="0" w:color="FF0000"> <w:end w:val="double" w:sz="24" w:space="0" w:color="FF0000"> <w:tl2br w:val="double" w:sz="24" w:space="0" w:color="FF0000"> </w:tcBorders> <w:tcPr> ''' tc = cell._tc tcPr = tc.get_or_add_tcPr() tcMar = OxmlElement('w:tcBorders') for k in ['top', 'start', 'bottom', 'end']: node = OxmlElement(f'w:{k}') node.set(qn('w:val'), 'inset') node.set(qn('w:sz'), '87') node.set(qn('w:color'), DEFAULT_COLORED_CELL_COLOR) tcMar.append(node) tcPr.append(tcMar)
def it_adds_to_doc_without_footer(self): document = Document(dir_pkg_path) document.remove_footers() footer = document.add_footer() footer_elm_tag = "w:footerReference" sentinel_sectPr = document._body._body.get_or_add_sectPr() footer_elms = sentinel_sectPr.findall(qn(footer_elm_tag)) assert len(footer_elms) == 1 assert footer assert len(footer.paragraphs) == 0 footer.add_paragraph("foobar") assert len(footer.paragraphs) == 1
def create_list(paragraph): """ Create unordered list in docx """ p_pr = paragraph._p.get_or_add_pPr() # pylint: disable=protected-access p_stylepr = p_pr.get_or_add_pStyle() p_style = OxmlElement('w:pStyle') p_style.set(qn('w:val'), str('List Paragraph')) p_stylepr.insert(0, p_style) num_pr = p_pr.get_or_add_numPr() ilvl = OxmlElement('w:ilvl') ilvl.set(qn('w:val'), str(0)) ilfo = OxmlElement('w:ilfo') ilfo.set(qn('w:val'), str(1)) num_pr.insert(0, ilvl) num_pr.insert(0, ilfo) p_pr.insert(0, num_pr) ind = OxmlElement('w:ind') ind.set(qn('w:left'), "1.2cm") ind.set(qn('w:right'), "0cm") p_pr.insert(0, ind) return paragraph
def firstpart(document): cur = time.strftime('%Y{y}%m{m}%d{d}', time.localtime(time.time())).format(y='年', m='月', d='日') #path = "../"+cur+"简报.docx" ''' try: document = Document(path) except: document = Document() ''' para = document.add_paragraph() run = para.add_run("") run.font.name = u'仿宋_GB2312' run._element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋_GB2312') run.font.bold = True run.font.color.rgb = RGBColor(0, 0, 0) pic = document.add_paragraph() picpath = os.path.abspath(os.path.dirname(__file__)) run = pic.add_run("") run.add_picture(picpath + '/OceanBrief/img/' + cur + 'wind.png', width=Inches(2.90)) run.add_picture(picpath + '/OceanBrief/img/' + cur + 'map.png', width=Inches(2.90)) forecast = read_weatherforecast() if (forecast[-1] == ';'): forecast = forecast[0:-1] para = document.add_paragraph() run = para.add_run("海域。" + forecast + "。") run.font.name = u'仿宋_GB2312' run._element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋_GB2312') run.font.size = Pt(12) run.font.color.rgb = RGBColor(0, 0, 0) document.add_page_break()
def add_internal_hyperlink_old(paragraph, url, name): tag = paragraph._element rt = docx.oxml.OxmlElement('w:r') fldChar = OxmlElement('w:fldChar') fldChar.set(qn('w:fldCharType'), 'begin') rt.append(fldChar) tag.append(rt) rt = docx.oxml.OxmlElement('w:r') instrText = OxmlElement('w:instrText') instrText.text = u' HYPERLINK \l "' + url + u'" ' rt.append(instrText) tag.append(rt) rt = docx.oxml.OxmlElement('w:r') fldChar = OxmlElement('w:fldChar') fldChar.set(qn('w:fldCharType'), 'separate') rt.append(fldChar) tag.append(rt) rt = docx.oxml.OxmlElement('w:r') rPr = docx.oxml.shared.OxmlElement('w:rPr') rstyle = docx.oxml.shared.OxmlElement('w:rStyle') rstyle.set(docx.oxml.shared.qn('r:id'), '6789') rstyle.set(docx.oxml.ns.qn('w:val'), url) rt.append(rPr) rPr.append(rstyle) rt.text = name tag.append(rt) rt = docx.oxml.OxmlElement('w:r') fldChar = OxmlElement('w:fldChar') fldChar.set(qn('w:fldCharType'), 'end') rt.append(fldChar) tag.append(rt)
def write_form(self, form_type: str): form_type_name_dict = {"overtime": "带加班", "normal": "正常"} form_type_head_dict = {"overtime": "签到表(含加班/调休/请假)", "normal": "签到表"} document = Document() document.styles["Normal"].font.name = u"宋体" # 微软雅黑 document.styles["Normal"].font.size = Pt(10.5) document.styles["Normal"]._element.rPr.rFonts.set( qn("w:eastAsia"), u"宋体") # 页面布局 sec = document.sections[0] # sections对应文档中的“节” sec.top_margin = Cm(2.3) sec.bottom_margin = Cm(2.3) sec.page_height = Cm(29.7) sec.page_with = Cm(21) # add header paragraph = document.add_paragraph() run = paragraph.add_run(form_type_head_dict.get(form_type)) font = run.font # set font name # font.name = u'宋体' # run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') font.size = Pt(16) # 三号 paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER paragraph_format = paragraph.paragraph_format # paragraph_format.line_spacing = 1.5 # 1.5倍行间距 # paragraph_format.space_after =Pt(0) #设置段后间距 paragraph = document.add_paragraph("姓名: 日期:{} 至 {}".format( self.__work_date_start, self.__work_date_end)) paragraph.alignment = WD_ALIGN_PARAGRAPH.LEFT paragraph_format = paragraph.paragraph_format paragraph_format.first_line_indent = Inches(0.3) # 首行缩进 paragraph_format.left_indent = Cm(3.7) # 左侧缩进3.7cm # paragraph_format.line_spacing = 1.5 # 1.5倍行间距 paragraph_format.space_after = Pt(0) # 设置段后间距 table = self.check_in_add_table(document, form_type) table.alignment = WD_TABLE_ALIGNMENT.CENTER document.save( os.path.join( "doc_file", "文思员工-{0}月签到表_新模版_{1}.docx".format( self.__input_month, form_type_name_dict.get(form_type)), )) logging.info("Done!")
def trans(): print("Enter the txt file name") txt_name = input() try: f = open(txt_name, 'rt', encoding='utf-8') except FileNotFoundError: print("Cannot find the file") return test = f.read() f.close() # 텍스트파일에 있는 내용을 받아옴 document = Document list = [] for i in test: if (i == "\n"): list.append() # list = test.split('\n') check = 0 for i in list: if (len(i) == 0): continue elif (check == 1): para = document.add_paragraph() run = para.add_run("○" + i) run.bold = True check = 0 else: document.add_paragraph(i) # "○김성원 위원"같은 태그가 붙을시 글씨체 bold 로 바꿔주고 붙혀넣어줌 style = document.styles['Normal'] font = style.font font.name = '함초롱바탕' style._element.rPr.rFonts.set(qn('w:eastAsia'), '함초롱바탕') font.size = Pt(10) # 글씨크기 변경 및 폰트 변경 document.add_page_break() section = document.sections[0] set_number_of_columns(section, 2) # 다단 설정(layout 설정) filename = os.path.splitext(txt_name)[0] docxfilename = filename + ".docx" document.save(docxfilename)
def create_word(self, data): # 打开文档 title = data['title'] categorys = data['files'] document = Document() # 加入不同等级的标题 document.add_heading(title, 0) for cat in categorys: document.add_heading(cat['name']) file_path = os.path.join(sys.path[0], cat['filename']) document.add_picture(file_path, width=Inches(7.5)) document.styles['Normal'].font.name = 'Consolas' document.styles['Normal'].font.size = Pt(8) document.styles['Normal']._element.rPr.rFonts.set( qn('w:eastAsia'), 'Consolas') table = document.add_table(rows=1, cols=3) hdr_cells = table.rows[0].cells hdr_cells[0].text = u'名称' hdr_cells[1].text = u'聚类' hdr_cells[2].text = u'会员数量' # 再增加3行表格元素 for cat in categorys: row_cells = table.add_row().cells row_cells[0].text = cat['name'] row_cells[1].text = str(cat['category']) row_cells[2].text = str(cat['volumns']) # 增加分页 document.add_page_break() # 保存文件 filename = title + '.docx' file_path = os.path.join(sys.path[0], filename) if os.path.exists(file_path): os.remove(file_path) document.save(file_path) with open(file_path, 'rb') as fp: data = fp.read().encode('base64') return data
def _add_caption(self, text, sequence_name=None): if not sequence_name: sequence_name = 'Figure' paragraph = self.insert_paragraph_after(text=None, style='Caption') paragraph.add_run('%s ' % sequence_name) new_fld = OxmlElement('w:fldSimple', attrs={ qn('w:instr'): r' SEQ %s \* ARABIC ' % sequence_name }) new_r = OxmlElement('w:r') new_r.add_t('0') new_fld.append(new_r) paragraph._p.append(new_fld) paragraph.add_run(": %s" % text) return paragraph
def insert_paragraph_before(p_cur, text): if text == None: return p_cur rp = p_cur.insert_paragraph_before(text) if len(rp.runs) > 0: rp.runs[0].font.size = Pt(15) # 字体大小 rp.runs[0].bold = False # 字体是否加粗 rp.runs[0].font.name = 'Times New Roman' # 控制是西文时的字体 rp.runs[0].element.rPr.rFonts.set(qn('w:eastAsia'), '楷体GBK_2312') # 控制是中文时的字体 rp.paragraph_format.first_line_indent = Cm(FIRST_LINE_INDENT) rp.line_spacing_rule = WD_LINE_SPACING.DOUBLE rp.paragraph_format.space_before = Pt(PARAGRAPH_SPACE_SIZE) rp.paragraph_format.space_after = Pt(PARAGRAPH_SPACE_SIZE) rp.line_spacing_rule = WD_LINE_SPACING.DOUBLE return rp
def set_text_by_colon(p,key_word,fillinword,help_word=''): r = p[0] while r is not None: if ':' in get_text(r) and keyword_is_previous_string(r,key_word): next_element = r.getnext() if next_element is None: next_element = insert_next_ritem(r,fillinword) elif get_text(next_element) is not '': next_element = insert_next_ritem(r,fillinword) elif check_tag_exist(next_element,'w:t'): next_element.find(qn('w:t')).text = fillinword else: p.remove(next_element) next_element = insert_next_ritem(r,fillinword) set_underline(next_element) r = r.getnext()
def write_doc(title, content, key): # with open('text.docx','w') as f: # f.write(content) document = Document() style = document.styles['Normal'] # 设置西文字体 style.font.name = 'Times New Roman' # 设置中文字体 style.element.rPr.rFonts.set(qn('w:eastAsia'), '微软雅黑') title_ = document.add_heading(title, 1) # 插入标题 title_.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER p = document.add_paragraph(content) # 插入段落 # p.add_run(' and some ') # p.add_run('italic.').italic = True document.save('{}-{}-2019年本科招生简章.docx'.format(key['id'], key['name'])) # 保存文档
def write_text(document, word, fontsize=12, fontname='微软雅黑', bold=False, italic=False, style=None): run = document.add_paragraph(style=style) run = run.add_run(word) run.font.size = Pt(fontsize) run.font.name = fontname #u'微软雅黑' r = run._element r.rPr.rFonts.set(qn('w:eastAsia'), fontname) # u'微软雅黑') run.bold = bold run.italic = italic return document
def CreateTable(title, cellList): p4 = document.add_paragraph() # 添加一个表格 行列 和格式 table = document.add_table(rows=2, cols=len(cellList), style='Table Grid') # 合并单元格 table.cell(0, 0).merge(table.cell(0, len(cellList) - 1)) # 对于合并的单元格,输入其中任何一个单元格都可以 table_run1 = table.cell(0, 0).paragraphs[0].add_run(title) # 表格标题 table_run1.font.name = u'微软雅黑' table_run1.element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑') table.cell(0, 0).paragraphs[0].aligment = WD_PARAGRAPH_ALIGNMENT.CENTER # 使用默认字体和格式 iCell = 0 for colName in cellList: table.cell(1, iCell).text = colName iCell = iCell + 1
def commonStytle(document, styleStr='commonStytle'): style = document.styles.add_style(styleStr, 1) # 设置字体尺寸 style.font.size = Pt(14) # 设置字体颜色 style.font.color.rgb = RGBColor(0x3f, 0x2c, 0x36) # 居中文本 # style.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER # # 设置中文字体 # style.font.name = '微软雅黑' # style._element.rPr.rFonts.set(qn('w:eastAsia'), '微软雅黑') # 设置段落样式为宋体 style.font.name = '宋体' style._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体') return style
def put_pic_to_cell(self): for i, row in enumerate(self.tabel.rows): for j, cell in enumerate(row.cells): for paragraph in cell.paragraphs: #####가운데 정렬!! paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER index = i * self.width + j if index < len(self.pics): run = paragraph.add_run() run.add_picture(self.pics[index], width=self.pic_width // 100 * 98, height=self.pic_height // 100 * 90) #####상하 방향에서 가운데 정렬 tc = cell._tc tcPr = tc.get_or_add_tcPr() tcVAlign = OxmlElement('w:vAlign') tcVAlign.set(qn('w:val'), "center") tcPr.append(tcVAlign)
def transcript_border(table): tbl = table._tbl rows = tbl.getchildren() lastRow = len(table.rows) - 1 for row in rows: if isinstance(row, CT_Row): cells = row.getchildren() if row.tr_idx == 0: # Top Row for cell in cells: if isinstance(cell, CT_Tc): tcPr = cell.tcPr tcBorders = OxmlElement('w:tcBorders') left = OxmlElement('w:left') left.set(qn('w:val'), 'nil') right = OxmlElement('w:right') right.set(qn('w:val'), 'nil') top = OxmlElement('w:top') top.set(qn('w:val'), 'nil') tcBorders.append(left) tcBorders.append(right) tcBorders.append(top) tcPr.append(tcBorders) elif row.tr_idx == lastRow: # Bottom Row for cell in cells: if isinstance(cell, CT_Tc): tcPr = cell.tcPr tcBorders = OxmlElement('w:tcBorders') top = OxmlElement('w:top') top.set(qn('w:val'), 'nil') tcBorders.append(top) tcPr.append(tcBorders) else: for cell in cells: if isinstance(cell, CT_Tc): tcPr = cell.tcPr tcBorders = OxmlElement('w:tcBorders') top = OxmlElement('w:top') top.set(qn('w:val'), 'nil') bottom = OxmlElement('w:bottom') bottom.set(qn('w:val'), 'nil') tcBorders.append(top) tcBorders.append(bottom) tcPr.append(tcBorders)
def set_run(run, font_size, bold, color, name): ''' 设置run对象 :param run: :param font_size: 字体大小 :param bold: 是否加粗 :param color: 字体颜色 :param name: 字体名 :return: ''' run.font.size = font_size run.bold = bold run.font.color.rgb = color run.font.name = name # 设置字体必须要下面2步 s = run._element s.rPr.rFonts.set(qn('w:eastAsia'), name)
def create_style(document, style_name, style_type, font_size=-1, font_color=None, font_name=None, align=None): """ 创建一个样式 :param align: :param document: :param style_name: 样式名称 :param style_type: 样式类型,1:段落样式, 2:字符样式, 3:表格样式 :param font_name: :param font_color: :param font_size: :return: """ if font_color is None: font_color = [] # 注意:必须要判断样式是否存在,否则重新添加会报错 style_names = [style.name for style in document.styles] if style_name in style_names: # print('样式已经存在,不需要重新添加!') return font_style = document.styles.add_style(style_name, style_type) # 字体大小 if font_size != -1: font_style.font.size = Pt(font_size) # 字体颜色 # 比如:[0xff,0x00,0x00] if font_color and len(font_color) == 3: font_style.font.color.rgb = RGBColor(font_color[0], font_color[1], font_color[2]) # 对齐方式 # 注意:段落、表格才有对齐方式 if style_type != 2 and align: font_style.paragraph_format.alignment = align # font_style.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # font_style.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT # font_style.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT # 中文字体名称 if font_name: font_style.font.name = font_name font_style._element.rPr.rFonts.set(qn('w:eastAsia'), font_name) return font_style
def draw_head(content='', level=1, font_family=u'宋体', font_color=(0x3f, 0x2c, 0x36), font_size=26, line_spacing=1, align=0): head = document.add_heading('', level=level) head.paragraph_format.line_spacing = line_spacing run = head.add_run(content) font = run.font font.color.rgb = RGBColor(*font_color) font.name = font_family run._element.rPr.rFonts.set(qn('w:eastAsia'), font_family) font.size = Pt(font_size) set_align(head, align)
def down(self): reqHeader = config.reqHeaderBDWK reqHeader['Referer'] = self.URL i = 1 docFileName = self.fileDir + self.WkInfo['title'] + '.' + self.WkInfo[ 'docType'] document = Document() # 创建doc(x)文档 while i <= self.WkInfo['totalPageNum']: jsonUrl = DownDocx.geturl(self.WkInfo['htmlUrls']['json'], i) if len(jsonUrl) == 0: logger.error('下载文档失败,查找URL失败!') return False jsonUrl = jsonUrl.replace('\\', '') jsonUrl = jsonUrl.replace(' ', '%20') req = urllib2.Request(jsonUrl, headers=reqHeader) res = urllib2.urlopen(req) res = res.read() jsonRet = res[res.find('(') + 1:res.rfind(')')] logger.info('打印一下,获取json数据内容为 ' + jsonRet) jsonRet = json.loads(jsonRet) # 再处理获取的页面内容 first = 0 for item in jsonRet['body']: if item['t'] != 'word': continue #if first == 0 or (item['ps'] and item['ps']['_enter'] == 1): if first == 0 or (item['ps'] and json_get( item, ['ps', '_enter'], '0') == 1): first = 1 pg = document.add_paragraph() #if item['ps'] and item['ps']['_enter'] == 1: if item['ps'] and json_get(item, ['ps', '_enter'], '0') == 1: continue run = pg.add_run(item['c']) # 添加格式;分析不出来,就统一宋体、五号 run.font.name = u'宋体' run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') run.font.size = Pt(10.5) # 下一页 if i < self.WkInfo['totalPageNum']: document.add_page_break() print 'Page' + str(i) #time.sleep(1) i += 1 document.save(docFileName) return True
def save_df_to_doc(document, test_df, word=None): """ 将结果按照dataframe的形式存入doc文件 :param document: 存入的文档类 :param test_df: 需要保存的df :return: """ document.styles['Normal'].font.name = u'宋体' document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') # add_paragraph表示添加一个段落 if word: document.add_paragraph(u'\n%s' % (word)) if len(test_df.columns) == 0: # document.add_paragraph(u'\n%s' % ('无')) return # 添加一个表格--行数和列数,行数多加一行,需要将列名同时保存 t = document.add_table(test_df.shape[0] + 1, test_df.shape[1], style=table_style) t.autofit = True t.alignment = WD_TABLE_ALIGNMENT.CENTER # 表格整体居中 # 将每列列名保存到表格中 for j in range(test_df.shape[-1]): t.cell(0, j).text = test_df.columns[j] t.cell(0, j).width = Inches(1.85) # 将每列数据保存到新建的表格中 for i in range(test_df.shape[0]): for j in range(test_df.shape[-1]): # 第一行保存的是列名,所以数据保存时,行数要加1 t.cell(i + 1, j).text = str(test_df.values[i, j]) for row in t.rows: for cell in row.cells: paragraphs = cell.paragraphs for paragraph in paragraphs: for run in paragraph.runs: font = run.font font.size = Pt(7.5) for col in range(test_df.shape[1]): t.cell(0, col).width = Inches(1.65) if t.cell(0, col).text == '策略名称': t.cell(0, col).width = Inches(3)
def __addParagraph__(self, doc, paragraph_content): """ 在word文档中添加段落 :param doc: 文档操作对象 :param paragraph_content: 段落内容 :return: """ paragraph = doc.add_paragraph() run = paragraph.add_run(paragraph_content) # 设置字体格式 run.font.name = '黑体' run._element.rPr.rFonts.set(qn('w:eastAsia'), '黑体') # 设置字体大小 run.font.size = Pt(14) # 是否加粗 run.font.bold = True
def add_text(self, p, wenzi='文字描述', size=11, bold=False, ziti=u'宋体', color='m'): ''' size = 5-72 ziti = u'宋体' or u'微软雅黑' bold=True 示例: import mytools from docx import Document import pandas as pd w = mytools.wordn cmcc_res = pd.read_csv('G:/cmcc_res.csv',encoding='gbk') document = Document() w.add_heading(document,'标题1') w.add_paragraph(document,'段落1') p = document.add_paragraph('') w.add_text(p,'添加的信息1') w.add_text(p,'添加的信息2') w.add_paragraph(document,'段落2') w.add_df(document,cmcc_res,'g',lists=[((1,1),(3,2)),((4,2),(6,3))]) document.save('demo.docx') ''' run1 = p.add_run(wenzi) # 使用add_run添加文字 run1.font.size = Pt(size) #字体大小设置,和word里面的字号相对应,小一 if bold: run1.font.bold = True run1.font.name = ziti if color == 'm': run1.font.color.rgb = RGBColor(0, 0, 0) elif color == 'r': run1.font.color.rgb = RGBColor(255, 0, 0) elif color == 'b': run1.font.color.rgb = RGBColor(0, 0, 255) else: run1.font.color.rgb = RGBColor(0, 0, 0) run1._element.rPr.rFonts.set(qn('w:eastAsia'), ziti) paragraph_format = p.paragraph_format paragraph_format.first_line_indent = Inches(0.25) paragraph_format.line_spacing = 1.5 # 1.5倍行间距
def add_internal_hyperlink(paragraph, url, name): tag = paragraph._element hyperlink = docx.oxml.OxmlElement('w:hyperlink') hyperlink.set(qn('w:anchor'), url) rt = docx.oxml.OxmlElement('w:r') rPr = docx.oxml.shared.OxmlElement('w:rPr') rstyle = docx.oxml.shared.OxmlElement('w:rStyle') rstyle.set(docx.oxml.shared.qn('w:val'), 'Internet') rPr.append(rstyle) rt.append(rPr) rt.text = name hyperlink.append(rt) tag.append(hyperlink)
def writeWord(all_content): # 创建文档对象 document = Document() # document.styles['Normal'].font.name = u'宋体' # 设置正文中文字体 microsoft_font = u'微软雅黑' # u 表示后面的字符串以 Unicode 格式进行编码 area = qn('w:eastAsia') document.styles['Normal'].font.name = microsoft_font document.styles['Normal']._element.rPr.rFonts.set(area, microsoft_font) for lines in all_content: if lines[0]: # 添加分页符 if lines[0] != '北京': document.add_page_break() # 设置文档标题,中文要用unicode字符串 p = document.add_paragraph() p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER run = p.add_run(u'\n'+lines[0]+'校友会\n') run.font.size = Pt(20) q = document.add_paragraph() q.add_run(u'职务:'+lines[1]+'\n') q.add_run(u'姓名:'+lines[2]+'\n') q.add_run(u'毕业学院:'+lines[3]+'\n') q.add_run(u'毕业时间:'+lines[4]+'\n') q.add_run(u'手机:'+lines[5]+'\n') q.add_run(u'工作单位:'+lines[6]+'\n') # 设置文档标题,中文要用unicode字符串 # document.add_heading(u'我的一个新文档',0) # 往文档中添加段落 # p = document.add_paragraph('This is a paragraph having some ') # p.add_run('bold ').bold = True # p.add_run('and some ') # p.add_run('italic.').italic = True # 添加一级标题 # document.add_heading(u'一级标题, level = 1',level = 1) # document.add_paragraph('Intense quote',style = 'IntenseQuote') # 添加图片,并指定宽度 #document.add_picture('e:/docs/pic.png',width = Inches(1.25)) # 保存文档 document.save('E:\\Yoc\\Course\\2021.docx')
def __set_run_style(run_obj, font_style): """设置 run 对象的格式,可以自定义段落中的某一些文字的样式""" # 字体的样式 font_color = font_style['font_color'] font_size = font_style['font_size'] font_name = font_style['font_name'] font_is_bold = font_style['font_is_bold'] font_is_italic = font_style['font_is_italic'] # 设置字体的样式 run_obj.font.color.rgb = RGBColor(font_color[0], font_color[1], font_color[2]) # 字体 rgb 颜色设置 run_obj.font.size = Pt(float(font_size)) # 字体大小 run_obj.bold = font_is_bold # 是否加粗 run_obj.font.italic = font_is_italic # 是否斜体 run_obj.font.name = font_name run_obj._element.rPr.rFonts.set( qn('w:eastAsia'), font_name) # fixme 弄不明白改一下字体的颜色,为什么用上面两句话
def on_btn_export_file_click(self): message = self.result_text.toPlainText() save_filename, ext = QtWidgets.QFileDialog.getSaveFileName( self, 'Save File', '', '*.docx') if not save_filename: return document = Document() p = document.add_paragraph('') for c in message: run = p.add_run(c) run.font.size = Pt(12) if c.isalpha() or c.isdigit(): run.font.name = 'Time New Roman' else: run.font.name = u'宋体' run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') document.save(save_filename)
def main(): inputfile = input("请输入您要提取的文档路径\n") outputfile = input("请输入您要输出的文档路径\n") words = readword(inputfile) print(words) document = Document() document.styles["Normal"].font.name=u"Times New Roman" document.styles["Normal"].font.element.rPr.rFonts.set(qn('w:eastAsia'),u'宋体') title = document.add_heading('There are words in {}'.format(inputfile.split('.')[0]),level = 0) title.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER pool = Pool(processes = 8) words_resultlist = [] for word in words: words_resultlist.append(pool.apply_async(getdictforword,args=(word,))) pool.close() pool.join() word_dicts = [] for word_dict in words_resultlist: word_dicts.append(word_dict.get()) print('开始截屏!') i=0 for word in words: capture(word) i=i+1 print('已完成{}%'.format(format((i/len(words))*100,'.2f'))) i=0 print('截屏结束!') for word in words: title_word = document.add_heading(word,level = 1) fayin_heading = document.add_heading('发音',level=2) fayin_paragraph = document.add_paragraph(word_dicts[i]['发音']) mean_heading = document.add_heading('释义',level=2) mean_paragraph = document.add_paragraph(word_dicts[i]['释义']) try: sentence1_heading = document.add_heading('例句1',level=2) sentence1_paragraph = document.add_paragraph( word_dicts[i]['例句1']) sentence2_heading = document.add_heading('例句2',level=2) sentence2_paragraph = document.add_paragraph( word_dicts[i]['例句2']) except: pass document.add_picture('images\\{}.png'.format(word),width = Inches(6.0)) document.add_page_break() i+=1 document.save(outputfile) print('finished')
def generate_apply_form(project_id: str, project_name: str, company: str, year: str, apply_info: dict): doc = Document('./template-forms/2 技术协作申请表.docx') doc.styles['Normal'].font.name = u'仿宋_GB2312' doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋_GB2312') table = doc.tables[0] run = table.rows[0].cells[1].paragraphs[0].add_run(apply_info['apply_dep']) run.font.size = Pt(12) run = table.rows[0].cells[4].paragraphs[0].add_run( apply_info['apply_time']) run.font.size = Pt(12) # 替换 项目号/项目名称:\n table.rows[1].cells[1].text = '' run = table.rows[1].cells[1].paragraphs[0].add_run('项目号/项目名称:\n' + project_id + '/' + project_name) run.font.size = Pt(12) run = table.rows[2].cells[1].paragraphs[0].add_run(company) run.font.size = Pt(12) # 替换 u'\u2713' + '□ 1)外场支持协助类\n□ 2)驻场技术支持类\n□ 3)设备验货支持类\n□ 4)项目文件评审类\n□ 5)专业技术支持类' table.rows[3].cells[1].text = '' run = table.rows[3].cells[1].paragraphs[0].add_run( apply_info['service_type']) run.font.size = Pt(12) # 替换 年 月 —— 年 月 table.rows[4].cells[1].text = '' run = table.rows[4].cells[1].paragraphs[0].add_run( apply_info['service_time']) run.font.size = Pt(12) # 替换 万 协作成本构成详见附表 table.rows[5].cells[1].text = '' run = table.rows[5].cells[1].paragraphs[0].add_run( apply_info['service_budget'] + '万 协作成本构成详见附表') run.font.size = Pt(12) save_project_form_file(company, year, project_id, project_name, '2 技术协作申请表', doc)
def full_ocr(request): print('start full ocr') start = time.time() pdf_file = list(request.json.get('input')[0].keys())[0] new_url = list(request.json.get('input')[0].values())[0] start_page = request.json.get('start_page') end_page = request.json.get('end_page') try: if pdf_file.lower().endswith('.pdf'): if start_page == end_page: pdf_images = [convert_from_path(pdf_file)[int(start_page) - 1]] else: pdf_images = convert_from_path(pdf_file)[int(start_page) - 1:int(end_page)] else: pdf_images = [Image.open(pdf_file)] except Exception as e: return response.json({ 'result': 'false', 'Documents': [], 'message': '请求失败' }) document = docx.Document() document.styles['Normal'].font.name = u'宋体' document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') for index, img_name in enumerate(pdf_images): print(index) if time.time() - start > 120 * len(pdf_images): return response.json({ 'result': 'false', 'Documents': [], 'message': '请求超时' }) else: document = single_ocr(document, img_name) files = os.path.splitext(pdf_file)[0] + '.docx' new_url = new_url + files.split('/')[-1] document.save(new_url) return response.json({ 'result': 'true', 'Documents': [{ 'new_url': new_url }], 'message': '请求成功' })
def down(self): reqHeader = config.reqHeaderBDWK reqHeader['Referer'] = self.URL i = 1 docFileName = self.fileDir + self.WkInfo['title'] + '.' + self.WkInfo['docType'] document = Document() # 创建doc(x)文档 while i <= self.WkInfo['totalPageNum']: jsonUrl = DownDocx.geturl(self.WkInfo['htmlUrls']['json'], i) if len(jsonUrl) == 0: logger.error('下载文档失败,查找URL失败!') return False jsonUrl = jsonUrl.replace('\\', '') jsonUrl = jsonUrl.replace(' ', '%20') req = urllib2.Request(jsonUrl, headers=reqHeader) res = urllib2.urlopen(req) res = res.read() jsonRet = res[res.find('(')+1 : res.rfind(')')] logger.info('打印一下,获取json数据内容为 ' + jsonRet) jsonRet = json.loads(jsonRet) # 再处理获取的页面内容 first = 0 for item in jsonRet['body']: if item['t'] != 'word': continue #if first == 0 or (item['ps'] and item['ps']['_enter'] == 1): if first == 0 or (item['ps'] and json_get(item, ['ps', '_enter'], '0') == 1): first = 1 pg = document.add_paragraph() #if item['ps'] and item['ps']['_enter'] == 1: if item['ps'] and json_get(item, ['ps', '_enter'], '0') == 1: continue run = pg.add_run(item['c']) # 添加格式;分析不出来,就统一宋体、五号 run.font.name = u'宋体' run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') run.font.size = Pt(10.5) # 下一页 if i < self.WkInfo['totalPageNum']: document.add_page_break() print 'Page' + str(i) #time.sleep(1) i += 1 document.save(docFileName) return True
def getter_fixture(self, request): choice_tag = request.param parent = self.parent_bldr(choice_tag).element tagname = 'w:%s' % choice_tag expected_choice = parent.find(qn(tagname)) # None if not found return parent, expected_choice
def _fields(self): fields = [] field = None # noinspection PyPep8Naming fldCharType = qn('w:fldCharType') instr = qn('w:instr') root = self._p.getroottree() instructions = '' for run in self.runs: for chld in run._r.getchildren(): tag = QName(chld.tag).localname if tag == 'fldChar': if chld.attrib.get(fldCharType) == 'begin': field = Field(self) field.xpath_start = root.getpath(run._r) elif chld.attrib.get(fldCharType) == 'end' and field is not None: if instructions: lex = shlex.shlex(instructions, posix=True) lex.whitespace_split = True lex.commenters = '' lex.escape = '' try: tokens = list(lex) except ValueError as e: raise ParserException(str(e) + chld.text, chld) field.code = tokens[0] fmt_target = None for token in tokens[1:]: if fmt_target is not None: field.format[fmt_target].append(token) fmt_target = None elif token.startswith('\\'): fmt_target = token[1:] else: field.extra.append(token) field.xpath_end = root.getpath(run._r) fields.append(field) field = None instructions = '' elif field: if tag == 't': field.default = chld.text elif tag == 'instrText' and chld.text.strip(): instructions += chld.text for fld in self._p.xpath('./w:fldSimple'): if fld.attrib.get(instr): field = Field(self) field.xpath_start = root.getpath(fld) field.xpath_end = root.getpath(fld) if fld.find(qn('w:r')): field.default = fld.find(qn('w:r'))[0].text lex = shlex.shlex(fld.attrib.get(instr), posix=True) lex.whitespace_split = True lex.commenters = '' lex.escape = '' tokens = list(lex) field.code = tokens[0] fmt_target = None for token in tokens[1:]: if fmt_target is not None: field.format[fmt_target].append(token) fmt_target = None elif token.startswith('\\'): fmt_target = token[1:] else: field.extra.append(token) fields.append(field) return fields
def getter_fixture(self): parent = self.parent_bldr(True).element zomChild = parent.find(qn('w:zomChild')) return parent, zomChild
def it_determines_class_used_for_elements_with_matching_tagname( self, xml_text): register_element_cls('a:foo', CustElmCls) foo = parse_xml(xml_text) assert type(foo) is CustElmCls assert type(foo.find(qn('a:bar'))) is etree._Element
def _clark_name(self): if ':' in self._attr_name: return qn(self._attr_name) return self._attr_name
def get_child_element_list(obj): return obj.findall(qn(self._nsptagname))
def saveDoc(self, py): """" формирование документа""" self.py = py document = docx.Document() sections = document.sections section = sections[0] section.left_margin = Inches(1) section.right_margin = Inches(0.65) section.page_width = Inches(8.3) section.page_height = Inches(11.7) styles = document.styles styles["List Number"].font.name = "Calibri" styles["Normal"].font.name = "Calibri" style = styles.add_style('table_z', WD_STYLE_TYPE.PARAGRAPH) style.base_style = styles['Normal'] style = styles["table_z"] style.font.bold = True style = styles.add_style('Code', WD_STYLE_TYPE.PARAGRAPH) style.base_style = styles['Normal'] style.font.name = "Courier New" style.font.size = Pt(10) styles = document.styles style = styles["Code"] p = style._element.get_or_add_pPr() numPr = OxmlElement('w:shd') # create number properties element numPr.set(qn('w:fill'), "FEF2E8") # set list type/indentation p.append(numPr) style = styles.add_style('hyperlink', WD_STYLE_TYPE.CHARACTER) style.base_style = styles['Default Paragraph Font'] style = styles['hyperlink'] style.font._element.get_or_add_rPr() style.font._element.get_or_add_unhideWhenUsed() style.font._element.get_or_add_semiHidden() style.font._element.rPr.get_or_add_u() style.font._element.rPr.u.val = WD_UNDERLINE.SINGLE style.font._element.rPr.get_or_add_color() style.font._element.rPr.color.val = RGBColor(2, 3, 226) style.font._element.rPr.color.themeColor = MSO_THEME_COLOR.HYPERLINK h = document.add_header() hp = h.add_paragraph(text1 % (self.py.nameProject.itemText(self.py.nameProject.currentIndex()), self.py.numBid.text())) hp.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER document.add_paragraph(u"Цель", style='table_z') document.add_paragraph(text2_0 % (self.py.nameProject.itemText(self.py.nameProject.currentIndex()))) h = document.add_paragraph('', style='List Bullet 3') h.add_run(text2_1 % (self.py.numberBid.text())).style = styles['hyperlink'] h.add_run(' - %s' % (self.py.specBid.text())) document.add_heading("Этап 1. Подготовка к публикации", level=2) document.add_paragraph(text3 % (self.py.timeIn.text(), self.py.timeOut.text(), self.py.dateIn.text())) make_table(document, self.py.tableView.model().cached, 0) document.add_paragraph() document.add_paragraph(text19_0) document.add_paragraph(text19_1) make_table(document, self.py.tableView.model().cached, 1) document.add_paragraph() document.add_paragraph(text20) document.add_paragraph() document.add_heading("Этап 2. Публикация изменений", level=2) document.add_paragraph() listSer = [] listApp = [] listVamish = [] test = [] if self.py.app1.text() != "": listSer = {self.py.app1.text(): self.py.ipAddress1.text()} listApp = [self.py.app1.text()] listVamish = [self.py.vamish1.text()] test = [self.py.test1.text()] if self.py.app2.text() != "": listSer[self.py.app2.text()] = self.py.ipAddress2.text() listApp.append(self.py.app2.text()) listVamish.append(self.py.vamish2.text()) test.append(self.py.test2.text()) if self.py.app3.text() != "": listSer[self.py.app3.text()] = self.py.ipAddress3.text() listApp.append(self.py.app3.text()) listVamish.append(self.py.vamish3.text()) test.append(self.py.test3.text()) if self.py.app4.text() != "": listSer[self.py.app4.text()] = self.py.ipAddress4.text() listApp.append(self.py.app4.text()) listVamish.append(self.py.vamish4.text()) test.append(self.py.test4.text()) document.add_paragraph(text5 % ", ".join(i for i in listSer), style='List Number') for i in range(0, len(listApp)): if (len(listApp) - 1) == i: serverPer = 0 else: serverPer = i + 1 com1 = bashIPPost % (listSer.get(listApp[serverPer]), self.py.portApp.text(), listSer.get(listApp[i])) com2 = bashIPPre % (listSer.get(listApp[i]), self.py.portApp.text(), listSer.get(listApp[serverPer])) document.add_paragraph(text6 % (self.py.nameProject.itemText(self.py.nameProject.currentIndex()), listApp[i], listApp[serverPer]), style='List Number') document.add_paragraph("%s \n%s" % (com1, com2), style="Code") document.add_paragraph(text7 % (listApp[i], self.py.numberRev.text()), style='List Number') h = document.add_paragraph('svn switch ', style="Code") h.add_run(self.py.svn.text()).style = styles['hyperlink'] h.add_run('\nsvn update') document.add_paragraph(text8 % (listApp[i]), style='List Number') document.add_paragraph("%s \n%s \n%s" % (text9, com2, com1), style="Code") if self.py.cache.isChecked(): document.add_paragraph(text10 % (listVamish[i]), style='List Number') document.add_paragraph(self.py.comandCache.text(), style="Code") document.add_paragraph(text12, style='List Number') document.add_paragraph(text13_0, style='List Bullet') document.add_paragraph(text13_1, style='List Bullet') document.add_paragraph(text13_2, style='List Bullet') document.add_paragraph(text13_3, style='List Bullet') for j in (self.py.tableView.model().cached): if j[2]: h = document.add_paragraph(style='List Paragraph') create_list(h, i) h.add_run(j[6]).style = styles['hyperlink'] document.add_paragraph(text14, style='List Number') document.add_paragraph(text17 % (test[i]), style="Code") s = ", ".join(c for c in listApp[0:i+1]) document.add_paragraph(text15 % s, style='List Number') document.add_paragraph(text20, style="List Number") document.add_heading("Этап 3. Мониторинг работы", level=2) document.add_paragraph(text4) return document
def __init__(self, fname, lname, cname, date, course, instructor, site, ta, completion): # Validate required arguments (note cname is not required (can be None)) x = 0 for arg in [fname, lname, date, course, instructor, site, ta, completion]: x+=1 if arg is None: print(x) raise ValueError("Required argument: {} was None.".format(arg)) # Reference only the arguments that will be used outside of the constructor self.fname = fname self.lname = lname self.cname = fname if cname is None else cname # Create the document self.document = Document() # Set margins section = self.document.sections[0] section.top_margin = Inches(1.5) section.bottom_margin = Inches(.75) section.left_margin = Inches(1) section.right_margin = Inches(1) # Title line at the very top title = self.document.add_paragraph() title.style.font.name = "Times New Roman" # All subsequent text is same font title.paragraph_format.space_after = Pt(11) title.paragraph_format.alignment = 1 # 1 means center title.add_run("CTY SUMMER PROGRAM FINAL EVALUATION").bold = True # Populate heading information including names, date, site, and course heading = self.document.add_paragraph() heading.paragraph_format.space_after = Pt(11) heading.paragraph_format.line_spacing = 1 heading.add_run("Student: " + fname + ' ' + lname + '\t') heading.add_run("Date: " + date + '\n') heading.add_run("Course: " + course + '\t') heading.add_run("Instructor: " + instructor + '\n') heading.add_run("Site: " + site + '\t') heading.add_run("Teaching Assistant: " + ta) #TODO I guess there is better API support for tab stops in python-docx now # https://python-docx.readthedocs.io/en/latest/dev/analysis/features/text/tab-stops.html # Insert a tab stop in the middle of the page for proper heading format. # Simplified code from: github.com/python-openxml/python-docx/issues/206 pTabs = OxmlElement('w:tabs') heading.paragraph_format.element.get_or_add_pPr().append(pTabs) tab_n = OxmlElement('w:tab') tab_n.set(qn('w:val'), "left") tab_n.set(qn('w:pos'), '5000') pTabs.append(tab_n) # Setup the intro paragraph introText = "Congratulations, " + self.cname + ', ' introText += "on " + completion + ' ' + course + '. ' introText += "Please see the enclosed course description for more detailed " introText += "information on the course." intro = self.document.add_paragraph(introText) intro.paragraph_format.space_after = Pt(11) intro.paragraph_format.line_spacing = 1 # Keep track of the number of body paragraphs in the document self.numParagraphs = 0
# document.add_heading(u'第' + character[current_chapter-1] + u'章', 2) # p = document.add_paragraph() # for verse in book: # if verse.ChapterSN != current_chapter: # current_chapter += 1 # document.add_heading(u'第' + character[current_chapter-1] + u'章', 2) # p = document.add_paragraph() # p.add_run(str(verse.VerseSN)).font.superscript = True # run = p.add_run(verse.Lection) # run.font.name = u"Adobe 楷体 Std R" # r = run._element # r.rPr.rFonts.set(qn('w:eastAsia'), u'Adobe 楷体 Std R') current_chapter = 1 p = document.add_paragraph() if chapter_num > 1: p.add_run(str(current_chapter)+' ').bold = True for verse in book: if verse.ChapterSN != current_chapter: current_chapter += 1 # document.add_heading(u'第' + character[current_chapter-1] + u'章', 2) p = document.add_paragraph() p.add_run(str(current_chapter)+' ').bold = True p.add_run(str(verse.VerseSN)).font.superscript = True run = p.add_run(verse.Lection) run.font.name = u"Adobe 楷体 Std R" r = run._element r.rPr.rFonts.set(qn('w:eastAsia'), u'Adobe 楷体 Std R') document.save(book_id.FullName+'.docx')
def toWord(_conList_g, _conList_t): d = datetime.datetime.now() curTime = (d.strftime('%Y_%m_%d')) document = Document() style1 = document.styles['Body Text'] font1 = style1.font font1.name = '宋体' font1.size = Pt(14) style2 = document.styles['Body Text 2'] font2 = style2.font font2.name = '宋体' font2.size = Pt(12) style3 = document.styles['Body Text 3'] font3 = style3.font font3.name = '宋体' font3.size = Pt(10.5) r = style1._element r.rPr.rFonts.set(qn('w:eastAsia'), '宋体') r = style2._element r.rPr.rFonts.set(qn('w:eastAsia'), '宋体') r = style3._element r.rPr.rFonts.set(qn('w:eastAsia'), '宋体') p = document.add_paragraph('') p.style = document.styles['Body Text'] p.add_run("全职信息").bold = True p.paragraph_format.line_spacing = 1 for i in _conList_g: p = document.add_paragraph('') p.style = document.styles['Body Text 2'] p.add_run(i['Company']).bold = True p.paragraph_format.line_spacing = 1 p = document.add_paragraph('') p.style = document.styles['Body Text 3'] p.add_run("学历:") if(i['Schooling'] is not None): p.add_run(i['Schooling']) else: p.add_run("不限") p.paragraph_format.line_spacing = 1 p = document.add_paragraph('') p.style = document.styles['Body Text 3'] p.add_run("专业:") if(i['Major'] is not None): p.add_run(i['Major']) else: p.add_run("不限") p.paragraph_format.line_spacing = 1 p = document.add_paragraph('') p.style = document.styles['Body Text 3'] p.add_run("工作地点:") if(i['District'] is not None): p.add_run(i['District']) else: p.add_run("详见公告") p.paragraph_format.line_spacing = 1 p = document.add_paragraph('') p.style = document.styles['Body Text 3'] p.add_run("招聘岗位:") if(i['RequireJob'] is not None): p.add_run(i['RequireJob']) else: p.add_run("详见公告") p.paragraph_format.line_spacing = 1 p = document.add_paragraph('') p.style = document.styles['Body Text 3'] p.add_run("简历投递方式:" + i['Method']) p.paragraph_format.line_spacing = 1 p = document.add_paragraph('') p.style = document.styles['Body Text 3'] p.add_run("截止日期:" + i['Deadline'][0:9]) p.paragraph_format.line_spacing = 1 p = document.add_paragraph('') p.paragraph_format.line_spacing = 1 p = document.add_paragraph('') p.style = document.styles['Body Text'] p.add_run("兼职信息").bold = True p.paragraph_format.line_spacing = 1 for i in _conList_t: p = document.add_paragraph('') p.style = document.styles['Body Text 2'] p.add_run(i['Company']).bold = True p.paragraph_format.line_spacing = 1 p = document.add_paragraph('') p.style = document.styles['Body Text 3'] p.add_run("学历:") if(i['Schooling'] is not None): p.add_run(i['Schooling']) else: p.add_run("不限") p.paragraph_format.line_spacing = 1 p = document.add_paragraph('') p.style = document.styles['Body Text 3'] p.add_run("专业:") if(i['Major'] is not None): p.add_run(i['Major']) else: p.add_run("不限") p.paragraph_format.line_spacing = 1 p = document.add_paragraph('') p.style = document.styles['Body Text 3'] p.add_run("工作地点:") if(i['District'] is not None): p.add_run(i['District']) else: p.add_run("详见公告") p.paragraph_format.line_spacing = 1 p = document.add_paragraph('') p.style = document.styles['Body Text 3'] p.add_run("招聘岗位:") if(i['RequireJob'] is not None): p.add_run(i['RequireJob']) else: p.add_run("详见公告") p.paragraph_format.line_spacing = 1 p = document.add_paragraph('') p.style = document.styles['Body Text 3'] p.add_run("简历投递方式:" + i['Method']) p.paragraph_format.line_spacing = 1 p = document.add_paragraph('') p.style = document.styles['Body Text 3'] p.add_run("截止日期:" + i['Deadline'][0:9]) p.paragraph_format.line_spacing = 1 p = document.add_paragraph('') p.paragraph_format.line_spacing = 1 document.save(curTime + '.docx')
def getter_fixture(self, request): zooChild_is_present = request.param parent = self.parent_bldr(zooChild_is_present).element zooChild = parent.find(qn('w:zooChild')) # None if not found return parent, zooChild
def then_the_tab_appears_at_the_end_of_the_run(context): r = context.run._r tab = r.find(qn('w:tab')) assert tab is not None
def then_type_is_page_break(context): attrib = context.last_child.attrib assert attrib == {qn('w:type'): 'page'}
def then_type_is_column_break(context): attrib = context.last_child.attrib assert attrib == {qn('w:type'): 'column'}
def first_fixture(self, request): present, matching, match = request.param element = self.rPr_bldr(present).element tagnames = self.nsptags(matching) matching_child = element.find(qn('w:%s' % match)) if match else None return element, tagnames, matching_child
def insert_before_fixture(self, request): body_cxml, text, style, expected_cxml = request.param body = element(body_cxml) paragraph = Paragraph(body.find(qn('w:p')), None) expected_xml = xml(expected_cxml) return paragraph, text, style, body, expected_xml