python 创建PDF文件

发布时间:2019-09-08 09:11:38编辑:auto阅读(1834)

    1.安装reportlab库

    http://www.reportlab.com/ftp/

    ubuntu可以直接 apt-get install python-reportlab

    2.实验

     

    1. >>> from reportlab.pdfgen import canvas 
    2. >>> def hello(): 
    3.     c = canvas.Canvas("hello World.pdf")  //指定pdf目录和文件名 
    4.     c.drawString(100,100,"helo World")    //输出区域及内容 
    5.     c.showPage() 
    6.     c.save()                                                //保存 

    综合案例

     

    1. >>> import datetime,subprocess 
    2. >>> from reportlab.pdfgen import canvas 
    3. >>> from reportlab.lib.units import inch 
    4. >>>  
    5. >>> def dir_report(): 
    6.     p = subprocess.Popen("dir",shell=True,stdout=subprocess.PIPE) 
    7.     return p.stdout.readlines() 
    8.  
    9. >>> def create_pdf(input,output="dir_report.pdf"): 
    10.     now = datetime.datetime.today() 
    11.     date = now.strftime("%h %d %Y %H:%M:%S"
    12.     c = canvas.Canvas(output) 
    13.     textobj = c.beginText() 
    14.     textobj.setTextOrigin(inch,11*inch) 
    15.     textobj.textLines(''''' 
    16.         This history sub dir and file is 
    17.         time is %s''' % date) 
    18.     for line in input: 
    19.         textobj.textLine(line.strip()) 
    20.     c.drawText(textobj) 
    21.     c.showPage() 
    22.     c.save() 
    23.  
    24.      
    25. >>> report = dir_report() 
    26. >>> create_pdf() 

     

     

     

关键字