Python使用reportlab将目录下所有的文本文件打印成pdf的方法

yipeiwu_com7年前Python基础

本文实例讲述了Python使用reportlab将目录下所有的文本文件打印成pdf的方法。分享给大家供大家参考。具体实现方法如下:

# -*- coding: utf8 -*- 
#~ #---------------------------------------------------------------------- 
import wlab #pip install wlab 
import reportlab.pdfbase.ttfonts 
#reportlab.pdfbase.pdfmetrics.registerFont(reportlab.pdfbase.ttfonts.TTFont('song', '/usr/share/fonts/cn/msjh.ttf')) 
#import reportlab.lib.fonts 
# 
from reportlab.pdfgen import canvas 
from reportlab.lib.units import inch 
# 
def file2pdf(FileName): 
  fpi=FileName.find('.') 
  if (fpi>0): 
    outputfn=FileName[0:fpi]+'.pdf' 
  else: 
    outputfn=FileName+'.pdf' 
  c = canvas.Canvas(outputfn) 
  #c.setFont('song',10) 
  textobject = c.beginText() 
  textobject.setTextOrigin(inch,11*inch) 
  file=open(FileName) 
  n=0 
  for line in file: 
    n=n+1 
    if(n<10): 
      nstr='0'+str(n) 
    else: 
      nstr=str(n) 
    line=nstr+': '+line.replace('  ','  ') 
    textobject.textLine(line.rstrip()) 
  c.drawText(textobject) 
  c.showPage() 
  c.save() 
# 
FileList=wlab.GetFileList('.',FlagStr=['.txt']) 
# 
for FileName in FileList: 
  file2pdf(FileName) 

希望本文所述对大家的Python程序设计有所帮助。

相关文章

python中的split()函数和os.path.split()函数使用详解

Python中有split()和os.path.split()两个函数: split():拆分字符串。通过指定分隔符对字符串进行切片,并返回分割后的字符串列表。 os.path.spli...

用Python批量把文件复制到另一个文件夹的实现方法

0 前言 大概是三个月前,有个人找我说要我帮忙写几行代码,功能是把一个文件夹里面的所有文件拆分成 200 个文件一个文件夹,很简单的。 我理解了之后,觉得还是挺简单的,花了半个小时写出...

Python2.x利用commands模块执行Linux shell命令

用Python写运维脚本时,经常需要执行linux shell的命令,Python中的commands模块专门用于调用Linux shell命令,并返回状态和结果,下面是commands...

对python列表里的字典元素去重方法详解

如下所示: def list_dict_duplicate_removal(): data_list = [{"a": "123", "b": "321"}, {"a": "12...

tensorflow入门:TFRecordDataset变长数据的batch读取详解

在上一篇文章tensorflow入门:tfrecord 和tf.data.TFRecordDataset的使用里,讲到了使用如何使用tf.data.TFRecordDatase来对tfr...