fpdf库把一组图片转换为PDF

电脑技术 电脑技术 986 人阅读 | 1 人回复 | 2022-05-14

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

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

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")
复制代码


回答|共 1 个

willsonlincake 发表于 2022-5-14 19:43:09| 字数 8 | 显示全部楼层

慢慢研究这些代码
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

热门推荐