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

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

WBOY
Release: 2016-06-06 11:17:33
Original
1587 people have browsed it

本文实例讲述了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) 

Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template