美丽心灵公益论坛

查看: 1695|回复: 1

fpdf库把一组图片转换为PDF

[复制链接]
累计签到:57 天
连续签到:1 天

981

主题

461

回帖

8037

积分

版主

Rank: 7Rank: 7Rank: 7

积分
8037
发表于 2022-5-14 19:42:56| 字数 1,207 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. import os
  2. import natsort
  3. from fpdf import FPDF

  4. page_format = 'letter'
  5. page_width_in_mm = 215.9
  6. page_height_in_mm = 279.4
  7. image_width_in_pixel = 2500
  8. image_height_in_pixel = 3300

  9. directory_name_list = os.listdir('INPUT')

  10. for directory_name in directory_name_list:
  11.     pdf = FPDF(orientation='P', unit='mm', format=page_format)
  12.     pdf.set_auto_page_break(0)
  13.     imagelist = [i for i in os.listdir('INPUT/' + directory_name) if i.endswith('jpg')]

  14.     for image in natsort.natsorted(imagelist):
  15.         width, height = float(image_width_in_pixel * 0.264583), float(image_height_in_pixel * 0.264583)

  16.         # given we are working with A4 format size
  17.         pdf_size = {'P': {'w': page_width_in_mm, 'h': page_height_in_mm},
  18.                     'L': {'w': page_height_in_mm, 'h': page_width_in_mm}}

  19.         # get page orientation from image size
  20.         orientation = 'P' if width < height else 'L'

  21.         #  make sure image size is not greater than the pdf format size
  22.         width = width if width < pdf_size[orientation]['w'] else pdf_size[orientation]['w']
  23.         height = height if height < pdf_size[orientation]['h'] else pdf_size[orientation]['h']
  24.         pdf.add_page(orientation=orientation)

  25.         pdf.set_left_margin(0.38)
  26.         pdf.set_right_margin(0.38)

  27.         pdf.image('INPUT/' + directory_name + '/' + image, 0, 0, width, height)

  28.     pdf.output("OUTPUT/" + directory_name + ".pdf", "F")
  29.     print(directory_name + ".pdf Ready")
复制代码


累计签到:57 天
连续签到:1 天

981

主题

461

回帖

8037

积分

版主

Rank: 7Rank: 7Rank: 7

积分
8037
 楼主| 发表于 2022-5-14 19:43:09| 字数 8 | 显示全部楼层
慢慢研究这些代码
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|免责及版权声明|关于|美丽心灵公益论坛

GMT+8, 2025-12-12 16:40 , Processed in 0.042831 second(s), 27 queries .

Powered by Discuz! X3.4

!copyright!

快速回复 返回顶部 返回列表