如何将文件夹中的所有JPG文件转换为PDF并将它们组合在一起? [英] How can I convert all JPG files in a folder to PDFs and combine them?
本文介绍了如何将文件夹中的所有JPG文件转换为PDF并将它们组合在一起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的文件夹(/img/)中有一些1924××2972 JPG文件.我想要1)将它们转换为PDF,以及2)将它们合并为一个PDF.但是我没有成功.我是python的新手.请让我知道如何进行.
I have a few 1924 × 2972 JPG files in a folder (/img/). I want to 1) Convert them to PDFs and 2) Combine them into a single PDF. But I am not successful. I am new to python. Please let me know how I can proceed.
from PIL import Image
import glob
from fpdf import FPDF #
imagelist = []
for filename in glob.glob('img/*.jpg'): #assuming jpg
im=Image.open(filename)
imagelist.append(im)
pdf = FPDF()
# imagelist is the list with all image filenames
for image in imagelist:
pdf.add_page()
pdf.image(image, 10,210,297)
pdf.output("yourfile.pdf", "F")
错误:
File "<ipython-input-39-9fb5b6258b5e>", line 1, in <module>
pdf.image(image, 10,210,297)
File "/Users/xyz/anaconda/lib/python3.6/site-packages/fpdf/fpdf.py", line 150, in wrapper
return fn(self, *args, **kwargs)
File "/Users/xyz/anaconda/lib/python3.6/site-packages/fpdf/fpdf.py", line 960, in image
if not name in self.images:
TypeError: unhashable type: 'JpegImageFile'
推荐答案
在第二个循环中,您需要实际引用每个jpg的路径:
In your second loop, you need to actually reference the path to each jpg:
pdf.image(image, 10,210,297)
此外,我认为您只需要每个图像的路径(而不是使用Image.open
打开每个图像.请尝试以下操作:
additionally, I think you just need the path to each image (rather than opening each image using Image.open
. Try the following:
import glob
from fpdf import FPDF #
imagelist = glob.glob('img/*.jpg')
pdf = FPDF()
# imagelist is the list with all image filenames
for image in imagelist:
pdf.add_page()
pdf.image(image, 10,210,297)
pdf.output("yourfile.pdf", "F")
这篇关于如何将文件夹中的所有JPG文件转换为PDF并将它们组合在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文