当前位置: 首页 > article >正文

使用python,自动实现将多个 JPG 文件转换为一个 PDF 文件

将多个 JPG 文件转换为一个 PDF 文件,并将文件命名为当前的年月日时分秒+pdf 扩展名

import os

from PIL import Image

from reportlab.lib.pagesizes import A4

from reportlab.pdfgen import canvas

from datetime import datetime

def convert_jpg_to_pdf(jpg_file_path):

    img = Image.open(jpg_file_path)

    img_width, img_height = img.size

    a4_width_px, a4_height_px = A4

    # 四周均留 10 像素

    available_width = a4_width_px - 20

    available_height = a4_height_px - 20

    aspect_ratio = img_height / img_width

    if aspect_ratio >= 1:

        new_width = available_width

        new_height = new_width * aspect_ratio

        if new_height > available_height:

            new_height = available_height

            new_width = new_height / aspect_ratio

    else:

        new_height = available_height

        new_width = new_height / aspect_ratio

        if new_width > available_width:

            new_width = available_width

            new_height = new_width * aspect_ratio

    resized_img = img.resize((int(new_width), int(new_height)), Image.LANCZOS)

    return resized_img

def create_pdf_with_images(folder_path):

    now = datetime.now()

    timestamp = now.strftime("%Y%m%d%H%M%S")

    pdf_file_path = os.path.join(folder_path, f'{timestamp}.pdf')

    c = canvas.Canvas(pdf_file_path, pagesize=A4)

    page_y = A4[1] - 10

    for filename in os.listdir(folder_path):

        if filename.endswith('.jpg'):

            jpg_file_path = os.path.join(folder_path, filename)

            resized_img = convert_jpg_to_pdf(jpg_file_path)

            page_x = 10

            c.drawImage(jpg_file_path, page_x, page_y, width=resized_img.width, height=resized_img.height)

            page_y -= resized_img.height

            if page_y < 10:

                c.showPage()

                page_y = A4[1] - 10

    c.save()

folder_path = r'D:\python\xxk'

create_pdf_with_images(folder_path)


http://www.kler.cn/news/363971.html

相关文章:

  • chrome清除https状态
  • WebSocket Secure (WSS)
  • 【Java SE 题库】LeetCode 热题 100--->两数之和
  • LeetCode Hot 100:图论
  • 参加了十多个面试,一个offer也没拿到...为什么?
  • 项目管理的主要内容包括哪些,项目工具有哪些
  • 11106 操作(c)
  • 【动态规划】子序列问题(上)
  • yarn的安装与使用以及与npm的区别(安装过程中可能会遇到的问题)
  • 动态规划-动归基础
  • 基于neo4j的新冠治疗和新冠患者轨迹的知识图谱问答系统
  • Hallo2 长视频和高分辨率的音频驱动的肖像图像动画 (数字人技术)
  • k8s 配置私有镜像仓库认证
  • repo将每个仓库回退到第一个commit的状态
  • 工具_Nginx
  • 学习记录:js算法(七十四):跳跃游戏II
  • Linux 移植_Home_Record
  • 【Linux系统】缺页中断机制
  • springboot餐厅点餐系统
  • hi3536上ffmpeg带rtmp移植
  • 【C++复习】经典笔试题
  • 【Linux系统内核探索】进程调度
  • 【设计模式】Liskov替换原则
  • 智谱清言AI
  • Java | Leetcode Java题解之第497题非重叠矩形中的随机点
  • Spring AOP的概念与使用