def _genRtfFile(questions): """ Given a list of Questions, return an RTF object which contains all data and can be rendered when appropriate using the renderRTF() function in this module. """ doc = rtf.Document() section = rtf.Section() doc.Sections.append(section) section.append("MULTIPLE CHOICE") section.append("") qNum = 1 for question in questions: q, a, ca = _getRTFFormattedContent(question, qNum) q = q.encode('rtfunicode') q = q.replace('\\u9?', '\t') ca = ca.encode('rtfunicode') ca = ca.replace('\\u9?', '\t') section.append(q) for ans in a: ans = ans.encode('rtfunicode') ans = ans.replace('\\u9?', '\t') section.append(ans) section.append(ca) qNum += 1 return doc
def _license_text(self, license_file): """ Generates rich text given a license file-like object :param license_file: file-like object :return: """ wordpad_header = textwrap.dedent(r''' {\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset255 Times New Roman;} {\*\generator Riched20 10.0.14393}\viewkind4\uc1 ''').strip().replace('\n', '\r\n') center_space = ' ' r = PyRTF.Renderer() doc = PyRTF.Document() ss = doc.StyleSheet sec = PyRTF.Section() doc.Sections.append(sec) is_blank = False paragraph_text = [''] for line in license_file: if not line or line.isspace(): is_blank = True if is_blank: # first element of paragraph_text is left-aligned, subsequent elements are centered is_centered = False for sec_line in paragraph_text: if is_centered: para_props = PyRTF.ParagraphPS( alignment=PyRTF.ParagraphPS.CENTER) p = PyRTF.Paragraph(ss.ParagraphStyles.Normal, para_props) p.append(sec_line) sec.append(p) elif sec_line: # first element may be nothing, but not whitespace sec.append(sec_line) is_centered = True is_blank = False paragraph_text = [''] if line.startswith(center_space): paragraph_text.append(line.strip()) is_blank = True else: paragraph_text[0] += ' ' + line paragraph_text[0] = paragraph_text[0].strip() f = StringIO() f.write(wordpad_header) r.Write(doc, f) return f.getvalue()
def setup_document (self, doc=None, ss=None): if doc: self.doc=doc else: self.doc = PyRTF.Document() if ss: self.ss=ss else: self.ss = self.doc.StyleSheet self.ss.ParagraphStyles.Normal.TextStyle.TextPropertySet.Font = self.ss.Fonts.TimesNewRoman self.ss.ParagraphStyles.Heading1.TextStyle.TextPropertySet.Bold = True if not hasattr(self.ss.ParagraphStyles, 'Heading3'): ps = PyRTF.ParagraphStyle('Heading 3', PyRTF.TextStyle(PyRTF.TextPropertySet(self.ss.Fonts.Arial, 22)), PyRTF.ParagraphPropertySet( space_before=240, space_after = 60), ) self.ss.ParagraphStyles.append( ps )
def _img(self, src): p = _upfile_path(src, None) if p.startswith(('http://', 'https://', 'ftp://')): obj = urllib.urlopen(p) ct = obj.headers['Content-Type'].lower() if ct[:6] == 'image/' and ct[6:] in ('png', 'jpg', 'jpeg', 'gif', 'bmp', 'tif'): t = ct[6:] fname = TMPFILE_PREFIX + '.png' open(fname, 'w+').write(obj.read()) if t != 'png': im = Image.open(fname) im = im.convert('RGB') im.save(fname, 'png') return PyRTF.Image(fname) return PyRTF.Image(p)
def save_rtf(self, file_name): import PyRTF DR = PyRTF.Renderer() doc = self.format_as_rtf() f = open(file_name, "w") DR.Write(doc, f) f.close()
def __init__(self, *a, **b): HTMLParser.__init__(self, *a, **b) self._doc = PyRTF.Document() self._ss = self._doc.StyleSheet self._section = self._doc.NewSection() self._queue = [] self._tag = ''
def add_paragraph(self, text, style=None): args = [] if style: args.append(style) else: args.append(self.ss.ParagraphStyles.Normal) p = PyRTF.Paragraph(*args) p.append(encode_text(text)) self.recsection.append(p)
def renderRTF(questions, fname): """ Format and write the list of Questions to a file with name /fname/. """ rtfObj = _genRtfFile(questions) renderer = rtf.Renderer() with open(fname, 'wb') as f: renderer.Write(rtfObj, f)
def main(): aves=model.getAves() doc3 = MakeExample3(aves=aves) DR = PyRTF.Renderer() DR.Write( doc3, OpenFile( 'gen_SingleAve' ) ) cmd=r'"%s%s.rtf"' %(initpath,'gen_SingleAve') #start "I:\Aptana Studio 3 Workspace\ncs_report\src\gen_singleave.rtf" #os.system(cmd) os.spawnl(os.P_NOWAIT,os.environ['COMSPEC'],"/C "+cmd)
def write_image(self, image): try: i = PyRTF.Image(write_image_tempfile(image)) self.recsection.append(i) self.add_paragraph(" ") except AttributeError: # If PyRTF has no attribute Image, this is an old version # and we can't do anything with images. pass
def write_license_rtf(self, rtf_path): # PyRTF and PyRTF-ng it seems do not support Unicode types # when they do this code should read the file using the codecs # module and create a Unicode RTF. if not p.exists(rtf_path): license_file = p.join(self.get_contents_dir(), 'LICENSE.txt') if p.exists(license_file): license_text = open(license_file, 'r').read() else: license_text = 'This software was not shipped with a license.' doc = PyRTF.Document() section = PyRTF.Section() doc.Sections.append(section) for paragraph in re.split("\n\n|\r\n\r\n", license_text): section.append(paragraph) renderer = PyRTF.Renderer() renderer.Write(doc, open(rtf_path, 'w'))
def getFont(nm): nm = nm.encode("gb2312") r = "" for unichar in nm: point = ord(unichar) if point < 128: r = r + unichar else: r = r + "\\'%x" % point return PyRTF.Font(r, "nil", 134, 2, '02010600030101010101')
def get_rtf(self): self._do_queue() DR = PyRTF.Renderer() fp = StringIO() try: DR.Write(self._doc, fp) return fp.getvalue() except: pass finally: fp.close()
def __init__ (self, rd, recipe_table, out, conv=None, progress_func=None): debug('rtf_exporter_multidoc starting!',5) self.doc = PyRTF.Document() exporter.ExporterMultirec.__init__(self, rd, recipe_table, out, one_file=True, ext='rtf', progress_func=progress_func, exporter=rtf_exporter, exporter_kwargs={'doc':self.doc, 'multidoc':True}) debug('rtf_exporter_multidoc done!',5)
def handle_data(self, data): t = self._tag data = data.encode('utf-8') if 'h1' <= t <= 'h3': size = [32, 24, 16][int(t[-1]) - 1] self._section.append('') self._section.append( PyRTF.Paragraph(PyRTF.TEXT(data, bold=True, size=size)) ) elif t in ('strong', 'b'): self._queue.append(PyRTF.B(data)) elif t in ('i', 'em'): self._queue.append(PyRTF.I(data)) elif t == 'u': self._queue.append(PyRTF.U(data)) elif t == 'code': for i in data.split('\n'): self._queue.append( PyRTF.Paragraph(PyRTF.TAB, PyRTF.TEXT(i, font=self._ss.Fonts.CourierNew)) ) elif t == 'latex': self._queue.append(self._center_p( PyRTF.TEXT( data, font=self._ss.Fonts.CourierNew, colour=self._ss.Colours.GreyDark ) )) elif t == 'blockquote': self._queue.append(PyRTF.TAB) elif t == 'th': # solution if data[0] == 'A': self._queue.append(PyRTF.TAB) self._queue.append(PyRTF.TEXT(data, bold=True)) self._queue.append(' ') elif t == 'p': self._queue.append(data) elif t not in ('html', 'head', 'style', 'script', 'table', 'tr', 'td', 'th'): self._queue.append(data) else: #print 'Skiping: ', data pass
def handle_starttag(self, tag, attrs): self._tag, self._attrs = tag, dict(attrs) if tag == 'img': src = self._attrs.pop('src', None) if src: try: self._queue.append(self._img(src)) except: pass elif tag == 'pdf:nextpage': self._queue.append( PyRTF.ParagraphPS().SetPageBreakBefore(True) )
def write_text(self, label, text): if not text: return self.add_paragraph(label, style=self.ss.ParagraphStyles.Heading2) pars = text.split("\n") # since we may have to deal with markup, we're going to handle this # on our own... for par in pars: p = PyRTF.Paragraph(self.ss.ParagraphStyles.Normal) # this code is partly copied from handle_markup in # exporter.py (a bit dumb, I know...) import pango, xml.sax.saxutils try: al, txt, sep = Pango.parse_markup(par, '\x00') except: al, txt, sep = Pango.parse_markup(xml.sax.saxutils.escape(par), '\x00') ai = al.get_iterator() more = True while more: fd, lang, atts = ai.get_font() chunk = xml.sax.saxutils.escape(txt.__getslice__(*ai.range())) fields = fd.get_set_fields() style_args = {'font': self.ss.Fonts.TimesNewRoman} if fields != 0: if 'style' in fields.value_nicks and fd.get_style( ) == Pango.Style.ITALIC: style_args['italic'] = True if 'weight' in fields.value_nicks and fd.get_weight( ) == Pango.Weight.BOLD: style_args['bold'] = True if [ att for att in atts if att.type == Pango.ATTR_UNDERLINE and att.value == Pango.Underline.SINGLE ]: style_args['underline'] = True p.append(PyRTF.Elements.TEXT(encode_text(chunk), **style_args)) more = next(ai) self.recsection.append(p)
def format_as_rtf(self): try: import PyRTF except ImportError: raise Sorry("The PyRTF module is not available.") doc = PyRTF.Document() ss = doc.StyleSheet section = PyRTF.Section() doc.Sections.append(section) p = PyRTF.Paragraph(ss.ParagraphStyles.Heading2) p.append("Table 1. Data collection and refinement statistics.") section.append(p) n_cols = len(self.columns) + 1 col_widths = [PyRTF.TabPS.DEFAULT_WIDTH * 3] * n_cols table = PyRTF.Table(*col_widths) header = [PyRTF.Cell(PyRTF.Paragraph(""))] anomalous_flag = False for column in self.columns: label = column.label if (column.anomalous_flag): label += "*" anomalous_flag = True column_label = PyRTF.Paragraph(ss.ParagraphStyles.Heading2, label) header.append(PyRTF.Cell(column_label)) table.AddRow(*header) for (stat_name, label, fstring, cif_tag) in keywords: row = [ PyRTF.Cell(PyRTF.Paragraph(ss.ParagraphStyles.Heading2, label)) ] n_none = 0 for column in self.columns: txt = column.format_stat(stat_name) if (txt is None): n_none += 1 p = PyRTF.Paragraph(ss.ParagraphStyles.Normal, PyRTF.ParagraphPS(alignment=2)) p.append(txt) row.append(PyRTF.Cell(p)) if (n_none == len(row) - 1): continue table.AddRow(*row) section.append(table) p = PyRTF.Paragraph(ss.ParagraphStyles.Normal) p.append("Statistics for the highest-resolution shell are shown in " + "parentheses.") section.append(p) return doc
def write_foot(self): if not self.multidoc: renderer = PyRTF.Renderer() renderer.Write(self.doc, self.out)
def write_head(self): self.recsection = PyRTF.Section(break_type=PyRTF.Section.PAGE) self.doc.Sections.append(self.recsection) self.add_paragraph("%s\n" % self.r.title, self.ss.ParagraphStyles.Heading1)
def write_footer(self): renderer = PyRTF.Renderer() renderer.Write(self.doc, self.ofi)
def MakeExample3(aves): doc = PyRTF.Document() ss = doc.StyleSheet ht = getFont( u"黑体" ) #PyRTF.Font(r"\'ba\'da\'cc\'e5",'nil',134,2,'02010600030101010101') st = getFont( u"宋体" ) #PyRTF.Font(r"\'cb\'ce\'cc\'e5",'nil',134,2,'02010600030101010101') ss.Fonts.append(ht) ss.Fonts.append(st) section = PyRTF.Section() doc.Sections.append(section) para_props = PyRTF.ParagraphPS(alignment=PyRTF.ParagraphPS.CENTER) # p = PyRTF.Paragraph( PyRTF.UNICODE(u'红外碳硫分析检验记录',size=32,font=ht),para_props) # section.append( p ) text_props = PyRTF.TextPropertySet() text_props.SetFont(ht) text_props.SetSize(32) u = PyRTF.Unicode(u'红外碳硫分析检验记录', text_props) p = PyRTF.Paragraph(u, para_props) section.append(p) p1 = PyRTF.Paragraph("") section.append(p1) # table = PyRTF.Table( 720 * 3, 720 * 1, int(720 * 2.5), int(720 * 2.5), #TabPS.DEFAULT_WIDTH * kd, 720 * 5, alignment=PyRTF.TabPS.CENTER) thin_edge = PyRTF.BorderPS(width=20, style=PyRTF.BorderPS.SINGLE) thick_edge = PyRTF.BorderPS(width=30, style=PyRTF.BorderPS.SINGLE) thin_frame1 = PyRTF.FramePS(thin_edge, thin_edge, thin_edge, thin_edge) thick_frame1 = PyRTF.FramePS(thick_edge, thin_edge, thin_edge, thin_edge) curFrame = thick_frame1 c1 = PyRTF.Cell(PyRTF.Paragraph(u"名称"), curFrame) c1.SetSpan(2) c3 = PyRTF.Cell(PyRTF.Paragraph(u"C%"), curFrame) c4 = PyRTF.Cell(PyRTF.Paragraph(u"S%"), curFrame) #c5 = Cell( Paragraph( str(s.user) ) ) c6 = PyRTF.Cell(PyRTF.Paragraph(u"分析时间"), curFrame) table.AddRow(c1, c3, c4, c6) from PyRTF import Cell, Paragraph, ParagraphPS for ave in aves: i = 0 for s in ave.singles: if i == 0: curFrame = thick_frame1 else: curFrame = thin_frame1 if len(ave.singles) > 1: c1 = Cell(Paragraph(s.name), curFrame) c2 = Cell(Paragraph(str(s.anaxuhao)), curFrame) c3 = Cell(Paragraph("%.5f" % s.c), curFrame) c4 = Cell(Paragraph("%.5f" % s.s), curFrame) #c5 = Cell( Paragraph( str(s.user) ) ) c6 = Cell(Paragraph(str(s.mdate)), curFrame) table.AddRow(c1, c2, c3, c4, c6) else: c1 = Cell(Paragraph(s.name), curFrame) c1.SetSpan(2) c3 = Cell(Paragraph("%.5f" % s.c), curFrame) c4 = Cell(Paragraph("%.5f" % s.s), curFrame) #c5 = Cell( Paragraph( str(s.user) ) ) c6 = Cell(Paragraph(str(s.mdate)), curFrame) table.AddRow(c1, c3, c4, c6) i = i + 1 curFrame = thin_frame1 if len(ave.singles) > 1: c1 = Cell( Paragraph(u"平均值", ParagraphPS(alignment=ParagraphPS.RIGHT)), curFrame) c1.SetSpan(2) #c2 = Cell( Paragraph("") ) c3 = Cell(Paragraph("%.5f" % ave.c), curFrame) c4 = Cell(Paragraph("%.5f" % ave.s), curFrame) #c5 = Cell( Paragraph( str(s.user) ) ) c6 = Cell(Paragraph(""), curFrame) table.AddRow(c1, c3, c4, c6) c1 = Cell( Paragraph(u"标准偏差", ParagraphPS(alignment=ParagraphPS.RIGHT)), curFrame) c1.SetSpan(2) #c2 = Cell( Paragraph("") ) c3 = Cell(Paragraph("%.5f" % ave.cstd), curFrame) c4 = Cell(Paragraph("%.5f" % ave.sstd), curFrame) #c5 = Cell( Paragraph( str(s.user) ) ) c6 = Cell(Paragraph(""), curFrame) table.AddRow(c1, c3, c4, c6) section.append(table) return doc
def __do_queue(self, queue): if queue: p = PyRTF.Paragraph(*queue) self._section.append(p)
def exportRtf(self): infoString = QtCore.QString("estrazione anagrafiche in word") reply = QtGui.QMessageBox.question( self, infoString, "Esportare solo le anagrafiche selezionate?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | QtGui.QMessageBox.Cancel, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: selected = self.selectSome(self.ui.tabella.selectedItems()) elif reply == QtGui.QMessageBox.No: selected = self.selectAll() else: return filexl = QFileDialog(self) #setto filexl in anymode cioe' ritorna il path del file anche se non esiste filexl.setFileMode(0) # filexl.setNameFilter("word(*.doc *.rtf)") nfile = filexl.getSaveFileName(self, "esporta anagrafiche in word", "", filter="(*.doc *.rtf)") DR = rtf.Renderer() doc = rtf.Document() ss = doc.StyleSheet n = 0 thin_edge = rtf.BorderPropertySet(width=20, style=rtf.BorderPropertySet.SINGLE) thick_edge = rtf.BorderPropertySet(width=80, style=rtf.BorderPropertySet.DOUBLE) mixed_frame = rtf.FramePropertySet(thin_edge, thick_edge, thin_edge, thick_edge) for i in enumerate(selected): section = rtf.Section() table = rtf.Table(rtf.TabPropertySet.DEFAULT_WIDTH * 7, rtf.TabPropertySet.DEFAULT_WIDTH * 3) #section.append(table) img = rtf.Image("pictures/logo.jpg") c1 = rtf.Cell(rtf.Paragraph(img)) c2 = rtf.Cell( rtf.Paragraph( ss.ParagraphStyles.Heading2, "Scheda anagrafica {0}".format(self.activeDb.getNameDb()))) table.AddRow(c1, c2) section.Header.append(table) oggi = datetime.date.today() section.Footer.append( rtf.Paragraph( ss.ParagraphStyles.Normal, "® Copyright Marketing & Telematica mail: [email protected] Data Esportazione: {0}/{1}/{2}" .format(oggi.day, oggi.month, oggi.year))) Id = i[1].data(1).toInt()[0] p = rtf.Paragraph(rtf.ParagraphPS().SetPageBreakBefore(True), '') section.append(p) doc = self.makeRtf(doc, section, Id, i[0] + 1, len((selected))) #doc=self.makeRtf(doc,section) ##print "scrivo",self.OpenFile( 'rtf/vero' ) DR.Write(doc, self.OpenFile(nfile))
def _center_p(self, *a): p = PyRTF.Paragraph(*a) s = self._ss.ParagraphStyles.Normal.Copy() s.ParagraphPropertySet.SetAlignment(3) # center p.Style = s return p