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 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
#read each line in the file.
#create a canvas objects,it can write the string
#in the 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.

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

It's simple that is,right?

No comments: