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基础知识小结之集合
Nov 25 Python
python脚本设置系统时间的两种方法
Feb 21 Python
Python实现爬取需要登录的网站完整示例
Aug 19 Python
python机器学习理论与实战(四)逻辑回归
Jan 19 Python
python让列表倒序输出的实例
Jun 25 Python
Python unittest 简单实现参数化的方法
Nov 30 Python
对python多线程SSH登录并发脚本详解
Feb 14 Python
Python利用sqlacodegen自动生成ORM实体类示例
Jun 04 Python
opencv3/C++ 平面对象识别&amp;透视变换方式
Dec 11 Python
python用pip install时安装失败的一系列问题及解决方法
Feb 24 Python
详解pycharm自动import所需的库的操作方法
Nov 30 Python
Python实现王者荣耀自动刷金币的完整步骤
Jan 22 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
建立动态的WML站点(一)
2006/10/09 PHP
PHP实现显示照片exif信息的方法
2014/07/11 PHP
php简单防盗链实现方法
2015/07/29 PHP
PHP从零开始打造自己的MVC框架之类的自动加载实现方法详解
2019/06/03 PHP
Yii框架页面渲染操作实例详解
2019/07/19 PHP
jQuery控制iFrame(实例代码)
2013/11/19 Javascript
Document.location.href和.replace的区别示例介绍
2014/03/04 Javascript
JQuery获取表格数据示例代码
2014/05/26 Javascript
jQuery表单域属性过滤器用法分析
2015/02/10 Javascript
jQuery添加和删除指定标签的方法
2015/12/16 Javascript
基于javascript实现根据身份证号码识别性别和年龄
2016/01/22 Javascript
Angularjs 实现分页功能及示例代码
2016/09/14 Javascript
vue组件学习教程
2017/09/09 Javascript
三分钟学会用ES7中的Async/Await进行异步编程
2018/06/14 Javascript
jQuery时间戳和日期相互转换操作示例
2018/12/07 jQuery
Js on及addEventListener原理用法区别解析
2020/07/11 Javascript
手把手带你搭建一个node cli的方法示例
2020/08/07 Javascript
[00:20]TI9不朽观赛名额抽取
2019/08/05 DOTA
Python、PyCharm安装及使用方法(Mac版)详解
2017/04/28 Python
使用Pyinstaller的最新踩坑实战记录
2017/11/08 Python
Python xlwt设置excel单元格字体及格式
2020/04/18 Python
python3.6 实现AES加密的示例(pyCryptodome)
2018/01/10 Python
浅述python中深浅拷贝原理
2018/09/18 Python
详解分布式任务队列Celery使用说明
2018/11/29 Python
Python小白垃圾回收机制入门
2020/06/09 Python
Django2.1.7 查询数据返回json格式的实现
2020/12/29 Python
html5 canvas实现圆形时钟代码分享
2013/12/25 HTML / CSS
moosejaw旗下的户外商品促销网站:Mountain Steals
2017/02/27 全球购物
广播电视新闻学专业应届生求职信
2013/10/08 职场文书
有个性的自我评价范文
2013/11/15 职场文书
领导班子四风对照检查材料思想汇报
2014/09/26 职场文书
基于go interface{}==nil 的几种坑及原理分析
2021/04/24 Golang
python实现会员信息管理系统(List)
2022/03/18 Python
【海涛dota】偶遇拉娜娅 质量局德鲁伊第一视角解说
2022/04/01 DOTA
《王国之心》迎来了发售的20周年, 野村哲发布贺图
2022/04/11 其他游戏
阿里云服务器(windows)手动部署FTP站点详细教程
2022/08/05 Servers