Thursday, November 27, 2008

How to write something in PDF by python

Did you ever meet this problem?your customer want to show their report by PDF format.I think so.I think the best lib to use is ReportLab ,you can download it from site and install it.Today I want to provide an simple example to illustrate how to use it,especially when you write something none standard character in it.Let's begin with a real example in our app,suppose you want to convert a text to a PDF.now you have a file at c:/log.txt,and you want to covert it to c:/h.pdf file.The code is :

#first we import necessary module.
from reportlab.pdfgen import canvas
#now,open the file which we want to covert to
f=open("c:/log.txt","rb")
#read each line in the file.
lines=f.readlines()
#create a canvas objects,it can write the string
#in the pdf
c=canvas.Canvas("c:/h.pdf")

#maybe the file we read was very big so we must
#consider that display them in multiple page
j=700 #for example it's height is 700 point
for row in lines:
#firstly, we do an encoding cover.
uniline=unicode(row,'latin-1')

if j==0:
j=700
#showPage method means,we want to write in next page
c.showPage()
else:
j=j-10
#drawString method will draw the text information in PDF
c.drawString(100, j, uniline.strip())
#don't forget close the file
f.close()
#don't forget save the canvas,otherwise,you can't see anything
#in the .pdf file
c.save()

It's simple that is,right?

No comments: