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


本文实例讲述了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程序设计有所帮助。

评论关闭