我正在从目录中获取图像列表,并且正在尝试将图像列表转换为 PDF。我正在获取它们的宽度和高度并使用 Image 模块。当程序运行并打开PDF文件时,图片看起来很大并且只有图片的一角。
from fpdf import FPDF
from PIL import Image
import glob
import os
image_directory = '/Users/myuser/pics/'
extensions = ('*.jpg','*.png','*.gif')
pdf = FPDF()
imagelist=[]
for ext in extensions:
imagelist.extend(glob.glob(os.path.join(image_directory,ext)))
for imageFile in imagelist:
cover = Image.open(imageFile)
width, height = cover.size
pdf.add_page()
# 1 px = 0.264583 mm (FPDF default is mm)
pdf.image(imageFile, 0, 0, float(width * 0.264583), float(height * 0.264583))
pdf.output(image_directory + "file.pdf", "F")
Run Code Online (Sandbox Code Playgroud)
小智 5
我认为问题在于图像大小超过了 pdf 大小(默认为 A4),纵向为 210 毫米 x 297 毫米,横向为反向。您应该检查并调整大小。您还可以根据页面的高度和宽度设置页面方向。
from fpdf import FPDF
from PIL import Image
import glob
import os
image_directory = '/Users/myuser/pics/'
extensions = ('*.jpg','*.png','*.gif')
pdf = FPDF()
imagelist=[]
for ext in extensions:
imagelist.extend(glob.glob(os.path.join(image_directory,ext)))
for imageFile in imagelist:
cover = Image.open(imageFile)
width, height = cover.size
# convert pixel in mm with 1px=0.264583 mm
width, height = float(width * 0.264583), float(height * 0.264583)
# given we are working with A4 format size
pdf_size = {'P': {'w': 210, 'h': 297}, 'L': {'w': 297, 'h': 210}}
# get page orientation from image size
orientation = 'P' if width < height else 'L'
# make sure image size is not greater than the pdf format size
width = width if width < pdf_size[orientation]['w'] else pdf_size[orientation]['w']
height = height if height < pdf_size[orientation]['h'] else pdf_size[orientation]['h']
pdf.add_page(orientation=orientation)
pdf.image(imageFile, 0, 0, width, height)
pdf.output(image_directory + "file.pdf", "F")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5633 次 |
| 最近记录: |