python FPDF没有正确调整大小

时间:2017-05-03 18:16:43

标签: python fpdf

我从目录中获取图像列表,我正在尝试将图像列表转换为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")

图像是左图像,右图是PDF图像 enter image description here

2 个答案:

答案 0 :(得分:1)

我认为问题在于图像尺寸超过pdf尺寸(默认为A4),即纵向为210mm x 297mm,横向为反面。您应该检查并调整大小。您还可以根据页面的高度和宽度设置页面方向。

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")

答案 1 :(得分:0)

pdf = FPDF(unit='mm')
for imageFile in selected_list:
    cover = Image.open(imageFile)
    width, height = cover.size
    width, height = float(width * 0.264583), float(height * 0.264583)
    pdf.add_page(format=(width, height))
    pdf.image(imageFile, 0, 0, width, height)
    name = "output.pdf"
    pdf.output(name)