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 相关文章推荐
Nginx搭建HTTPS服务器和强制使用HTTPS访问的方法
Aug 16 Python
一张图带我们入门Python基础教程
Feb 05 Python
Python中shutil模块的学习笔记教程
Apr 04 Python
利用Python读取文件的四种不同方法比对
May 18 Python
matplotlib绘制动画代码示例
Jan 02 Python
python使用pil库实现图片合成实例代码
Jan 20 Python
如何将 awk 脚本移植到 Python
Dec 09 Python
浅谈selenium如何应对网页内容需要鼠标滚动加载的问题
Mar 14 Python
Keras - GPU ID 和显存占用设定步骤
Jun 22 Python
Python中使用aiohttp模拟服务器出现错误问题及解决方法
Oct 31 Python
通过Python pyecharts输出保存图片代码实例
Nov 25 Python
python中tkinter复选框使用操作
Nov 11 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
利用php+mysql来做一个功能强大的在线计算器
2010/10/12 PHP
PHP URL路由类实例
2013/11/12 PHP
超强多功能php绿色集成环境详解
2017/01/25 PHP
PHP基于socket实现的简单客户端和服务端通讯功能示例
2017/07/10 PHP
地震发生中逃生十大法则
2008/05/12 Javascript
javascript 兼容FF的onmouseenter和onmouseleave的代码
2008/07/19 Javascript
My Desktop :) 桌面式代码
2008/12/29 Javascript
jquery右下角弹出提示框示例代码
2013/10/08 Javascript
JavaScript strike方法入门实例(给字符串加上删除线)
2014/10/17 Javascript
jQuery中slideUp 和 slideDown 的点击事件
2015/02/26 Javascript
鼠标悬停小图标显示大图标
2016/01/22 Javascript
js实现商品抛物线加入购物车特效
2020/11/18 Javascript
深入理解 JavaScript 中的 JSON
2017/04/06 Javascript
ES6中的Promise代码详解
2017/10/09 Javascript
用vue快速开发app的脚手架工具
2018/06/11 Javascript
Python中List.count()方法的使用教程
2015/05/20 Python
Python中方法链的使用方法
2016/02/23 Python
浅析python中SQLAlchemy排序的一个坑
2017/02/24 Python
python 截取 取出一部分的字符串方法
2017/03/01 Python
计算机二级python学习教程(2) python语言基本语法元素
2019/05/16 Python
新西兰杂志订阅:isubscribe
2019/08/26 全球购物
鞋类设计与工艺专业销售求职信
2013/11/01 职场文书
小班秋游活动方案
2014/02/22 职场文书
交通安全责任书范本
2014/07/24 职场文书
校外活动方案
2014/08/28 职场文书
员工工作及收入证明
2014/10/28 职场文书
幼儿园大班见习报告
2014/10/31 职场文书
2014年文艺部工作总结
2014/11/17 职场文书
搞笑婚庆主持词
2015/06/29 职场文书
新年寄语2016
2015/08/17 职场文书
学习社交礼仪心得体会
2016/01/22 职场文书
2016年教师师德师风承诺书
2016/03/25 职场文书
python中os.path.join()函数实例用法
2021/05/26 Python
Python 实现定积分与二重定积分的操作
2021/05/26 Python
浅谈resultMap的用法及关联结果集映射
2021/06/30 Java/Android
Win7/8.1用户可以免费升级到Windows 11系统吗?
2021/11/21 数码科技