Python3将jpg转为pdf文件的方法示例
本文实例讲述了Python3将jpg转为pdf文件的方法。分享给大家供大家参考,具体如下:
#coding=utf-8 #!/usr/bin/envpython """ convertimagetopdffile """ #Author:mrbeann importos importsys importglob importplatform fromreportlab.lib.pagesizesimportletter,A4,landscape fromreportlab.platypusimportSimpleDocTemplate,Image fromreportlab.lib.unitsimportinch fromreportlab.pdfgenimportcanvas fromreportlabimportrl_settings fromPILimportImage importimportlib,sys #importlib.reload(sys) #sys.setdefaultencoding("utf-8") deftopdf(path,recursion=None,pictureType=None,sizeMode=None,width=None,height=None,fit=None,save=None): """ Parameters ---------- path:string pathofthepictures recursion:boolean NoneorFalsefornorecursion Trueforrecursiontochildrenfolder wethertorecursionornot pictureType:list typeofpictures,forexample:jpg,png... sizeMode:int Noneor0forpdf'spagesizeisthebiggestofallthepictures 1forpdf'spagesizeistheminofallthepictures 2forpdf'spagesizeisthegivenvalueofwidthandheight tochoosehowtodeterminethesizeofpdf width:int widthofthepdfpage height:int heightofthepdfpage fit:boolean NoneorFalseforfitthepicturesizetopagesize Trueforkeepthesizeofthepictures wethertokeepthepicturesizeornot save:string pathtosavethepdf """ ifplatform.system()=='Windows': path=path.replace('\\','/') ifpath[-1]!='/': path=(path+'/') ifrecursion==True: foriinos.listdir(path): ifos.path.isdir(os.path.abspath(os.path.join(path,i))): topdf(path+i,recursion,pictureType,sizeMode,width,height,fit,save) filelist=[] ifpictureType==None: filelist=glob.glob(os.path.join(path,'*.jpg')) else: foriinpictureType: filelist.extend(glob.glob(os.path.join(path,'*.'+i))) maxw=0 maxh=0 ifsizeMode==NoneorsizeMode==0: foriinfilelist: im=Image.open(i) ifmaxwim.size[0]: maxw=im.size[0] ifmaxh>im.size[1]: maxh=im.size[1] else: ifwidth==Noneorheight==None: raiseException("nowidthorheightprovid") maxw=width maxh=height maxsize=(maxw,maxh) ifsave==None: filename_pdf=path+path.split('/')[-2] else: filename_pdf=save+path.split('/')[-2] filename_pdf=filename_pdf+'.pdf' c=canvas.Canvas(filename_pdf,pagesize=maxsize) l=len(filelist) foriinrange(l): (w,h)=maxsize width,height=letter iffit==True: c.drawImage(filelist[i],0,0) else: c.drawImage(filelist[i],0,0,maxw,maxh) c.showPage() c.save() defmain(): topdf(u'F:/gitplace/jpg2pdf/test',pictureType=['png','jpg'],save='F:/gitplace/jpg2pdf/test/新建文件夹') if__name__=='__main__': main()
GitHub地址:https://github.com/mrbeann/jpg2pdf
更多Python相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。