python将图片转换为pdf

本文介绍了一种使用Python将图片批量转换为PDF的方法,并提供了详细的代码实现。该方法利用reportlab库来创建PDF文档,并通过PIL库处理图片旋转等问题。但转换后的PDF文件体积较大,存在优化空间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需要先安装reportlab,这个安装容易报错,解决办法如下:
https://blog.youkuaiyun.com/zhezhebie/article/details/88846824

python将图片转换为pdf,代码如下:

from reportlab.pdfgen import canvas
from reportlab.lib.units import inch, cm
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Image, PageBreak
from reportlab.lib.pagesizes import A4,A3,A2,A1, legal, landscape
from reportlab.lib.utils import ImageReader
import PIL.Image,PIL.ExifTags
from os import listdir
import os,re
import time
from reportlab.lib.units import inch

def img_search(mypath, filenames):
    for lists in os.listdir(mypath):
        path = os.path.join(mypath,lists)
        if os.path.isfile(path):
            expression = r'[\w]+\.(jpg|png|jpeg)$'
            if re.search(expression, path, re.IGNORECASE):
                filenames.append(path)
        elif os.path.isdir(path):
            img_search(path, filenames)


def img_search1(mypath, filenames):
    for lists in os.listdir(mypath):
        path = os.path.join(mypath,lists)
        if os.path.isfile(path):
            a = path.split('.')
            if a[-1] in ['jpg', 'png', 'JPEG']:
                filenames.append(path)
        elif os.path.isdir(path):
            img_search1(path,filenames)


def rotate_img_to_proper(image):
    try:
        # image = Image.open(filename)
        if hasattr(image, '_getexif'):  # only present in JPEGs
            for orientation in PIL.ExifTags.TAGS.keys():
                if PIL.ExifTags.TAGS[orientation] == 'Orientation':
                    break
            e = image._getexif()  # returns None if no EXIF data
            if e is not None:
                #log.info('EXIF data found: %r', e)
                exif = dict(e.items())
                orientation = exif[orientation]
                # print('found, ',orientation)

                if orientation == 3:
                    image = image.transpose(Image.ROTATE_180)
                elif orientation == 6:
                    image = image.transpose(Image.ROTATE_270)
                elif orientation == 8:
                    image = image.rotate(90,expand=True)
    except:
        pass
    return image


def main(src_folder=None):
    output_file_name = 'out.pdf'
    #save_file_name = 'ex.pdf'
    #doc = SimpleDocTemplate(save_file_name, pagesize=A1,
    #                     rightMargin=72, leftMargin=72,
    #                     topMargin=72, bottomMargin=18)
    imgDoc = canvas.Canvas(output_file_name)#pagesize=letter
    imgDoc.setPageSize(A4)
    document_width,document_height = A4
    if src_folder is None: mypath = input('Input the image folder please:')
    else: mypath = src_folder
    filenames=[]
    start = time.clock()
    img_search(mypath, filenames)
    end = time.clock()
    print('find file cost time: ', end-start, 'find files: ', len(filenames))
    # for f in filenames:
    #     print(f)
    for image in filenames:
        try:
            image_file = PIL.Image.open(image)
            image_file = rotate_img_to_proper(image_file)

            image_width, image_height = image_file.size
            print('img size:', image_file.size)
            if not(image_width>0 and image_height>0):
                raise Exception
            image_aspect = image_height/float(image_width)
            #Determins the demensions of the image in the overview
            print_width  = document_width
            print_height = document_width*image_aspect
            imgDoc.drawImage(ImageReader(image_file),document_width-print_width,
                         document_height-print_height,width=print_width,
                             height=print_height,preserveAspectRatio=True)
            #inform the reportlab we want a new page
            imgDoc.showPage()
        except Exception as e:
            print('error:',e,image)
    imgDoc.save()
    print('Done')


if __name__ == '__main__':
    main(src_folder='C:\\Users\\Administrator\\Desktop\\L1-U5-L3');

在这里插入图片描述

有个问题,转换成pdf后,体积变非常大.只是测试了一下.图片32张,单张图片100kb左右,加起来3M左右,但是转换完pdf之后pdf文件有26M,这是不能接受的.

代码: https://github.com/ilovin/stitch_img_to_pdf/blob/master/stitch_img.py
https://blog.youkuaiyun.com/qq_37051001/article/details/86138308

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值