The Python platform's excellent PDF report Class library Reportlab. It is not part of the Python standard class library, so you must manually download the class library package and install it:
Yum Install Python-reportlab-y
This article will cover the basic common APIs in Reportlab and use canvas to draw a neat PDF report. For more information, refer to the Official User guide of Reportlab.
Example one, generating a paragraph of text
#!/usr/bin/pythonfrom reportlab.pdfgen Import Canvasdef hello (): c = Canvas. Canvas ("Helloworld.pdf") c.drawstring (100,100, "Hello,world") C.showpage () C.save () Hello ()
Example two, generating a PDF of a single file
#需要安装字体 yum install wqy-* -y#!/usr/bin/pythonimport datetimeimport Subprocessimport codecsfrom reportlab.pdfgen import canvasfrom reportlab.lib.units import inchfrom reportlab.lib.pagesizes import A4, landscapeimport Reportlab.pdfbase.ttfonts reportlab.pdfbase.pdfmetrics.registerfont ( Reportlab.pdfbase.ttfonts.TTFont (' song ', '/usr/share/fonts/cn/msjh.ttf ')) import Reportlab.lib.fonts def disk1_report (): p1 = subprocess. Popen ("cat cmd1.log ", shell=true,stdout=subprocess. PIPE) return p1.stdout.readlines () def create_pdf (input,output= "Disk1.pdf"): now = datetime.datetime.today () date = now.strftime ("%h %d %y %h:%m:%s") c = canvas. Canvas (OUTPUT,PAGESIZE=A4) c.setfont (' song ', Ten) textobject = c.begintext () Textobject.settextorigin (1*inCh,11*inch) textobject.textlines ("disk capacity report: %s " % date ) for line in input: textobject.textline (Line.strip ()) c.drawText ( Textobject) c.showpage () c.save () Report = disk1_report () create_pdf (report)
Example three, looping through multiple files under the specified directory ()
#!/usr/bin/pythonimport osimport os.pathimport datetimeimport subprocessfrom reportlab.lib.pagesizes import a4, landscapefrom reportlab.pdfgen import canvasfrom reportlab.lib.units import inchlogdir = "/var/www/device/check_log" for root,dirs,filenames in os.walk (LogDir): for filename in filenames: v = root+os.sep+filename os.environ[' file '] = str (v) def disk_report (): p = Subprocess. Popen ("cat $file ", shell=true,stdout=subprocess. PIPE) return p.stdout.readlines () def Create_pdf (input,output= "/var/www/device/check_pdf/" +filename+ ". pdf"): now = datetime.datetime.today () date = noW.strftime ("%h %d %y %h:%m:%s") c = canvas. Canvas (OUTPUT,PAGESIZE=A4) textobject = c.begintext () textobject.settextorigin (1*inch,11*inch) textobject.textlines ("Disk Capacity Report: %s " % date ) for Line in input: textobject.textline (Line.strip ()) c.drawtext (Textobject) c.showpage () c.save () report = disk_report () create_pdf ( Report
This article is from the "World" blog, make sure to keep this source http://xiajie.blog.51cto.com/6044823/1677550
Generate PDF files using Python