Python生成pdf文件的方法

yipeiwu_com5年前Python基础

本文实例演示了Python生成pdf文件的方法,是比较实用的功能,主要包含2个文件。具体实现方法如下:

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)

感兴趣的读者可以调试运行一下,对不足之处加以改进,以实现功能的最佳应用!

相关文章

python如何求解两数的最大公约数

题目: 给定两个自然数,求这两个数的最大公约数。 分析: 单看题目的话,非常简单,我们可以循环遍历自然数,如果能够整除两个自然数,就把这个数记下来,在这些记录中找到最大的一个。 但...

python3下使用cv2.imwrite存储带有中文路径图片的方法

由于imwrite前使用编码在python3中已经不适用,可用imencode代替,以下代码是从视频中获取第2帧保存在中文文件夹下的实例: cap = cv2.VideoCaptur...

python中reader的next用法

python中有个csv包(build-in),该包有个reader,按行读取csv文件中的数据 reader.next()作用:打印csv文件中的第一行标题header (python...

python 统计文件中的字符串数目示例

题目: 一个txt文件中已知数据格式为: C4D C4D/maya C4D C4D/su C4D/max/AE 统计每个字段出现的次数,比如C4D、maya 先读取文件,将文件中的数据抽...

Python实现利用163邮箱远程关电脑脚本

学了一个礼拜Python之后写的,代码很粗糙,只是为了完成利用163邮箱远程关电脑功能。直接把代码发上来吧。要执行的话得先安装一些模块,看import语句。 十月初写的,写完这个之后就没...