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

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

WBOY
WBOYOriginal
2016-06-06 11:17:331565browse

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn