首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用Python生成pdf文件

使用Python生成pdf文件

作者头像
py3study
发布2020-01-06 12:11:23
3.1K0
发布2020-01-06 12:11:23
举报
文章被收录于专栏:python3python3

    Python平台的优秀PDF报表类库Reportlab。它不属于Python的标准类库,所以必须手动下载类库包并安装:       yum install python-reportlab -y     这篇文章将介绍reportlab中基本常用的api,使用canvas画出一份整洁的PDF报表。详细内容参考reportlab的官方user guide

示例一、生成一段文字

#!/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()

示例二、生成单个文件的pdf

#需要安装字体 yum install wqy-* -y
#!/usr/bin/python
import datetime
import subprocess
import codecs
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import A4, landscape
import 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',10)
 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)

示例三、循环生成指定目录下的多个文件()

#!/usr/bin/python
import os
import os.path
import datetime
import subprocess
from reportlab.lib.pagesizes import A4, landscape
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
logdir = "/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)
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
腾讯云 BI
腾讯云 BI(Business Intelligence,BI)提供从数据源接入、数据建模到数据可视化分析全流程的BI能力,帮助经营者快速获取决策数据依据。系统采用敏捷自助式设计,使用者仅需通过简单拖拽即可完成原本复杂的报表开发过程,并支持报表的分享、推送等企业协作场景。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档