1. 程式人生 > >PyRTF模組生成rtf的一些常見用法

PyRTF模組生成rtf的一些常見用法

python 寫一些報告,常用的可用win32 com的模組編寫WORD,不過不能居於linux平臺,這裡採用PyRTF模組來生成rtf。對一些基礎操作,做些記錄!指令碼可以優化,對於一些呼叫可以寫成函式形式,這裡是為了理解方便!

注意:參考PyRTF模組例項

#!/usr/bin/python

#--Pyrtf example 1

import sys
sys.path.append('/home/tanght/PyRTF-0.45')
from PyRTF import *

##sample file
SAMPLE_TEXT='''THIS IS A SAMPLE PARAGRAPH
               THIS IS A SAMPLE PARAGRAPH
			   THIS IS A SAMPLE PARAGRAPH
			   THIS IS A SAMPLE PARAGRAPH'''

def pyrtfexample1():
##style
    doc = Document()
	handle = doc.StyleSheet
	section = Section()
	doc.Sections.append(section)
##Set Header,Footer	
	section.Header.append('THIS IS THE HEADER')
	section.Footer.append('THIS IS THE FOOTER')
	
##Title Font
	pa = Paragraph(handle.ParagraphStyles.Heading1)
	pa.append('USAGE OF PyRTF')
	section.append(pa)
	
##Content Font
	pa = Paragraph(handle.ParagraphStyles.Normal)
	pa.append('This is an example by using PyRTF module to create a rtf')
	section.append(pa)
	pa = Paragraph()
	pa.append(SAMPLE_TEXT)
	section.append(pa)
##Create cell form	
    pa = Paragraph(handle.ParagraphStyles.Heading1)
	pa.append('HOW TO FORM CELL')
	section.append(pa)
	
	thin_edge = BorderPS( width=20, style=BorderPS.SINGLE)
	thick_edge = BorderPS( width=80, style=BorderPS.SINGLE)
	
	thin_frame = FramePS( thin_edge, thin_edge, thin_edge, thin_edge)
	thick_frame = FramePS( thick_edge, thick_edge, thick_edge, thick_edge)
	
	table = Table( TabPS.DEFAULT_WIDTH * 3, TabPS.DEFAULT_WIDTH * 3, TabPS.DEFAULT_WIDTH * 3)
	c1 = Cell( Paragraph('R1C1'),thin_frame)
	c2 = Cell( Paragraph('R1C2'),thin_frame)
	c3 = Cell( Paragraph('R1C3'),thin_frame)
	table.AddRow( c1, c2, c3 )
	
	c1 = Cell( Paragraph('R2C1'),thin_frame)
	c2 = Cell( Paragraph('R2C2'),thin_frame)
	c3 = Cell( Paragraph('R2C3'),thin_frame)
	table.AddRow( c1, c2, c3 )
	section.append(table)
	section.append(' ')
	section.append(' ')
	table2 = Table( TabPS.DEFAULT_WIDTH * 2, TabPS.DEFAULT_WIDTH * 3, TabPS.DEFAULT_WIDTH * 4)
	c1 = Cell( Paragraph('R1C1'),thick_frame)
	c2 = Cell( Paragraph('R1C2'),thick_frame)
	c3 = Cell( Paragraph('R1C3'),thick_frame)
	table2.AddRow( c1, c2, c3 )
	section.append(table2)
##Insert Next PAGE	
	pa = Paragraph(handle.ParagraphStyles.Normal,ParagraphPS().SetPageBreakBefore( True ))
	pa.append('THIS IS THE SECOND PAGE')
	section.append(pa)
	pa = Paragraph(handle.ParagraphStyles.Heading1)
	pa.append('HOW TO COLOR THE WORD!')
	section.append(' ')
	section.append(pa)
##Colour Font	
	tps = TextPS( colour=handle.Colours.Red )
	text = Text( 'RED WORD',tps )
	pa.append('HERE IS THE',text)
	section.append(pa)
##Insert Image	
	pa.append('HOW TO INSERT A IMAGE')
	section.append(pa)
	image = Image ( './test.jpg' )
	section.append( Paragraph(image) )
		
    return doc
	
def OpenFile(name):
    return file( '%s.rtf' % name,'w')


if __name__ == '__main__':
     DR = Renderer()
	 doc1 = pyrtfexample1()
	 DR.Write( doc1, OpenFile('test') )
	 print 'Finished'