python生成pdf文件代码实例

发布时间:2019-11-05编辑:脚本学堂
python生成pdf文件的方法,借助canvas与inch模块生成pdf文件的代码,测试可用的pdf文件生成代码,感兴趣的朋友参考下。

python生成pdf文件

python生成pdf文件的方法

1、pdf.py文件:
 

复制代码 代码示例:
#!/usr/bin/python
from reportlab.pdfgen import canvas
def hello():
    c = canvas.Canvas("helloworld.pdf")
    c.drawString(100,100,"Hello,World")
    c.showPage()
    c.save()
hello()

2、diskreport.py文件:
 

复制代码 代码示例:
#!/usr/bin/env python
import subprocess
import datetime
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
def disk_report():
    p = subprocess.Popen("df -h", shell=True, stdout=subprocess.PIPE)
#   print p.stdout.readlines()
    return p.stdout.readlines()
def create_pdf(input, output="disk_report.pdf"):
    now = datetime.datetime.today()
    date = now.strftime("%h %d %Y %H:%M:%S")
    c = canvas.Canvas(output)
    textobject = c.beginText()
    textobject.setTextOrigin(inch, 11*inch)
    textobject.textLines('''Disk Capcity Report: %s''' %date)
    for line in input:
  textobject.textLine(line.strip())
    c.drawText(textobject)
    c.showPage()
    c.save()
report = disk_report()
create_pdf(report)

综合实现代码:
 

pdf.py
#!/usr/bin/python
from reportlab.pdfgen import canvas
def hello():
  c = canvas.Canvas("helloworld.pdf")
  c.drawString(100,100,"Hello,World")
  c.showPage()
  c.save()
hello()

diskreport.py
#!/usr/bin/env python
import subprocess
import datetime
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch

def disk_report():
  p = subprocess.Popen("df -h", shell=True, stdout=subprocess.PIPE)
  #print p.stdout.readlines()
  return p.stdout.readlines()

def create_pdf(input, output="disk_report.pdf"):
  now = datetime.datetime.today()
  date = now.strftime("%h %d %Y %H:%M:%S")
  c = canvas.Canvas(output)
  textobject = c.beginText()
  textobject.setTextOrigin(inch, 11*inch)
  textobject.textLines('''Disk Capcity Report: %s''' %date)
  for line in input:
     textobject.textLine(line.strip())
  c.drawText(textobject)
  c.showPage()
  c.save()
report = disk_report()
create_pdf(report) #生成pdf

另外,还可以用py2pdf模块生成pdf文件,方便好用。
py2pdf地址:http://python.net/~gherman/py2pdf.html