Python3将jpg转为pdf文件的方法示例


Posted in Python onDecember 13, 2019

本文实例讲述了Python3将jpg转为pdf文件的方法。分享给大家供大家参考,具体如下:

#coding=utf-8
#!/usr/bin/env python
"""
convert image to pdf file
"""
#Author: mrbeann 
import os
import sys
import glob
import platform
from reportlab.lib.pagesizes import letter, A4, landscape
from reportlab.platypus import SimpleDocTemplate, Image
from reportlab.lib.units import inch
from reportlab.pdfgen import canvas
from reportlab import rl_settings
from PIL import Image
import importlib,sys
#importlib.reload(sys)
#sys.setdefaultencoding("utf-8")
def topdf(path,recursion=None,pictureType=None,sizeMode=None,width=None,height=None,fit=None,save=None):
  """
  Parameters
  ----------
  path : string
      path of the pictures
  recursion : boolean
        None or False for no recursion
        True for recursion to children folder
        wether to recursion or not
  pictureType : list
         type of pictures,for example :jpg,png...
  sizeMode : int
      None or 0 for pdf's pagesize is the biggest of all the pictures
      1 for pdf's pagesize is the min of all the pictures
      2 for pdf's pagesize is the given value of width and height
      to choose how to determine the size of pdf
  width : int
      width of the pdf page
  height : int
      height of the pdf page
  fit : boolean
      None or False for fit the picture size to pagesize
      True for keep the size of the pictures
      wether to keep the picture size or not
  save : string
      path to save the pdf
  """
  if platform.system() == 'Windows':
    path = path.replace('\\','/')
  if path[-1] != '/':
    path = (path + '/')
  if recursion == True:
    for i in os.listdir(path):
      if os.path.isdir(os.path.abspath(os.path.join(path, i))):
        topdf(path+i,recursion,pictureType,sizeMode,width,height,fit,save)
  filelist = []
  if pictureType == None:
    filelist = glob.glob(os.path.join(path, '*.jpg'))
  else:
    for i in pictureType:
      filelist.extend(glob.glob(os.path.join(path, '*.'+i)))
  maxw = 0
  maxh = 0
  if sizeMode == None or sizeMode == 0:
    for i in filelist:
      im = Image.open(i)
      if maxw < im.size[0]:
        maxw = im.size[0]
      if maxh < im.size[1]:
        maxh = im.size[1]
  elif sizeMode == 1:
    maxw = 999999
    maxh = 999999
    for i in filelist:
      im = Image.open(i)
      if maxw > im.size[0]:
        maxw = im.size[0]
      if maxh > im.size[1]:
        maxh = im.size[1]
  else:
    if width == None or height == None:
      raise Exception("no width or height provid")
    maxw = width
    maxh = height
  maxsize = (maxw,maxh)
  if save == 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)
  for i in range(l):
    (w, h) =maxsize
    width, height = letter
    if fit == True:
      c.drawImage(filelist[i] , 0,0)
    else:
      c.drawImage(filelist[i] , 0,0,maxw,maxh)
    c.showPage()
  c.save()
def main():
  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程序设计有所帮助。

Python 相关文章推荐
Python程序设计入门(5)类的使用简介
Jun 16 Python
Python写的服务监控程序实例
Jan 31 Python
Python命令行参数解析模块optparse使用实例
Apr 13 Python
django轻松使用富文本编辑器CKEditor的方法
Mar 30 Python
python中字符串的操作方法大全
Jun 03 Python
python如何求解两数的最大公约数
Sep 27 Python
python实现根据指定字符截取对应的行的内容方法
Oct 23 Python
Python基于OpenCV实现人脸检测并保存
Jul 23 Python
python pyinstaller打包exe报错的解决方法
Nov 02 Python
python装饰器相当于函数的调用方式
Dec 27 Python
python读取hdfs上的parquet文件方式
Jun 06 Python
聊聊pytorch测试的时候为何要加上model.eval()
May 23 Python
如何使用python3获取当前路径及os.path.dirname的使用
Dec 13 #Python
PyQt5多线程刷新界面防假死示例
Dec 13 #Python
wxpython多线程防假死与线程间传递消息实例详解
Dec 13 #Python
python-web根据元素属性进行定位的方法
Dec 13 #Python
python Jupyter运行时间实例过程解析
Dec 13 #Python
Python time库基本使用方法分析
Dec 13 #Python
使用python 将图片复制到系统剪贴中
Dec 13 #Python
You might like
正则表达式语法
2006/10/09 Javascript
Smarty分页实现方法完整实例
2016/05/11 PHP
使用Codeigniter重写insert的方法(推荐)
2017/03/23 PHP
laravel5.6实现数值转换
2019/10/23 PHP
详解Laravel服务容器的绑定与解析
2019/11/05 PHP
Javascript 二维数组
2009/11/26 Javascript
javascript对talbe进行动态添加、删除、验证实现代码
2012/03/29 Javascript
js为鼠标添加右击事件防止默认的右击菜单弹出
2013/07/29 Javascript
IE6-8中Date不支持toISOString的修复方法
2014/05/04 Javascript
js代码实现的加入收藏效果并兼容主流浏览器
2014/06/23 Javascript
node.js中的console.time方法使用说明
2014/12/09 Javascript
js获取内联样式的方法
2015/01/27 Javascript
javascript实现简单的二级联动
2015/03/19 Javascript
原生javascript实现图片无缝滚动效果
2016/02/12 Javascript
jQuery使用serialize()表单序列化时出现中文乱码问题的解决办法
2016/07/27 Javascript
javascript之with的使用(阿里云、淘宝使用代码分析)
2016/10/11 Javascript
js实现类bootstrap模态框动画
2017/02/07 Javascript
JS实现简易的图片拖拽排序实例代码
2017/06/09 Javascript
bootstrap treeview 扩展addNode方法动态添加子节点的方法
2017/11/21 Javascript
Vue插件打包与发布的方法示例
2018/08/20 Javascript
代码实例ajax实现点击加载更多数据图片
2018/10/12 Javascript
three.js实现炫酷的全景3D重力感应
2018/12/30 Javascript
微信小程序简单的canvas裁剪图片功能详解
2019/07/12 Javascript
[02:28]DOTA2 2017国际邀请赛小组赛回顾
2017/08/09 DOTA
python使用opencv对图像mask处理的方法
2019/07/05 Python
Python实现图片查找轮廓、多边形拟合、最小外接矩形代码
2020/07/14 Python
Python3基于plotly模块保存图片表格
2020/08/03 Python
加拿大时尚床上用品零售商:QE Home | Quilts Etc
2018/01/22 全球购物
美国领先的家庭智能音响系统品牌:Sonos
2018/07/20 全球购物
澳大利亚香水在线商店:City Perfume
2020/09/02 全球购物
两年的个人工作自我评价
2014/01/10 职场文书
自愿离婚协议书范本
2014/09/13 职场文书
2014年敬老院工作总结
2014/12/08 职场文书
成绩单家长意见
2015/06/03 职场文书
2015年秋季校长开学典礼致辞
2015/07/29 职场文书
PyCharm配置KBEngine快速处理代码提示冲突、配置命令问题
2021/04/03 Python