Python 从图像列表创建 PDF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27327513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create PDF from a list of images
提问by Macabeus
Is there any practical way to create a PDF from a list of images files, using Python?
有没有什么实用的方法可以使用 Python 从图像文件列表中创建 PDF?
In Perl I know that module. With it I can create a PDF in just 3 lines:
在 Perl 中,我知道那个模块。有了它,我只需 3 行就可以创建一个 PDF:
use PDF::FromImage;
...
my $pdf = PDF::FromImage->new;
$pdf->load_images(@allPagesDir);
$pdf->write_file($bookName . '.pdf');
I need to do something very similar to this, but in Python. I know the pyPdfmodule, but I would like something simple.
我需要做一些与此非常相似的事情,但是在 Python 中。我知道pyPdf模块,但我想要一些简单的东西。
@Edit
@编辑
If you came through Google, here's the code:
如果你是通过谷歌来的,这里是代码:
from fpdf import FPDF
from PIL import Image
def makePdf(pdfFileName, listPages, dir = ''):
if (dir):
dir += "/"
cover = Image.open(dir + str(listPages[0]) + ".jpg")
width, height = cover.size
pdf = FPDF(unit = "pt", format = [width, height])
for page in listPages:
pdf.add_page()
pdf.image(dir + str(page) + ".jpg", 0, 0)
pdf.output(dir + pdfFileName + ".pdf", "F")
采纳答案by Ilya Vinnichenko
Install FPDF for Python:
pip install fpdf
Now you can use the same logic:
现在您可以使用相同的逻辑:
from fpdf import FPDF
pdf = FPDF()
# imagelist is the list with all image filenames
for image in imagelist:
pdf.add_page()
pdf.image(image,x,y,w,h)
pdf.output("yourfile.pdf", "F")
You can find more info at the tutorial pageor the official documentation.
回答by Tanveer Alam
pgmagickis a GraphicsMagick(Magick++)
binding for Python.
pgmagick是GraphicsMagick(Magick++)
Python的绑定。
It's is a Python wrapper for for ImageMagick(or GraphicsMagick).
它是ImageMagick(或GraphicsMagick)的 Python 包装器。
import os
from os import listdir
from os.path import isfile, join
from pgmagick import Image
mypath = "\Images" # path to your Image directory
for each_file in listdir(mypath):
if isfile(join(mypath,each_file)):
image_path = os.path.join(mypath,each_file)
pdf_path = os.path.join(mypath,each_file.rsplit('.', 1)[0]+'.pdf')
img = Image(image_path)
img.write(pdf_path)
Sample input Image:
PDF looks like this:
pgmagick iinstallation instruction for windows:
Windows 的 pgmagick iinstallation 说明:
1) Download precompiled binary packages from the Unofficial Windows Binaries for Python Extension Packages(as mentioned in the pgmagick web page) and install it.
1) 从用于 Python 扩展包的非官方 Windows 二进制文件(如 pgmagick 网页中所述)下载预编译的二进制包并安装它。
Note: Try to download correct version corresponding to your python version installed in your machine and whether its 32bit installation or 64bit.
注意:尝试下载与您机器上安装的python版本相对应的正确版本,无论是32位安装还是64位安装。
You can check whether you have 32bit or 64bit python by just typing python at your terminal and press Enter..
您可以通过在终端输入 python 并按 Enter 来检查您是否拥有 32 位或 64 位 python。
D:\>python
ActivePython 2.7.2.5 (ActiveState Software Inc.) based on
Python 2.7.2 (default, Jun 24 2011, 12:21:10) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
So it has python version 2.7
and its of 32 bit (Intel)] on win32
so you have to downlad and install pgmagick?0.5.8.win32?py2.7.exe
.
所以它有python version 2.7
它的32 bit (Intel)] on win32
所以你必须下载并安装pgmagick?0.5.8.win32?py2.7.exe
。
These are the following available Python Extension Packages for pgmagick:
以下是pgmagick可用的 Python 扩展包:
- pgmagick?0.5.8.win?amd64?py2.6.exe
- pgmagick?0.5.8.win?amd64?py2.7.exe
- pgmagick?0.5.8.win?amd64?py3.2.exe
- pgmagick?0.5.8.win32?py2.6.exe
- pgmagick?0.5.8.win32?py2.7.exe
- pgmagick?0.5.8.win32?py3.2.exe
- pgmagick?0.5.8.win?amd64?py2.6.exe
- pgmagick?0.5.8.win?amd64?py2.7.exe
- pgmagick?0.5.8.win?amd64?py3.2.exe
- pgmagick?0.5.8.win32?py2.6.exe
- pgmagick?0.5.8.win32?py2.7.exe
- pgmagick?0.5.8.win32?py3.2.exe
2) Then you can follow installation instruction from here.
2) 然后您可以按照此处的安装说明进行操作。
pip install pgmagick
An then try to import it.
然后尝试导入它。
>>> from pgmagick import gminfo
>>> gminfo.version
'1.3.x'
>>> gminfo.library
'GraphicsMagick'
>>>
回答by Daisuke Harada
How about this??
这个怎么样??
from fpdf import FPDF
from PIL import Image
import glob
import os
# set here
image_directory = '/path/to/imageDir'
extensions = ('*.jpg','*.png','*.gif') #add your image extentions
# set 0 if you want to fit pdf to image
# unit : pt
margin = 10
imagelist=[]
for ext in extensions:
imagelist.extend(glob.glob(os.path.join(image_directory,ext)))
for imagePath in imagelist:
cover = Image.open(imagePath)
width, height = cover.size
pdf = FPDF(unit="pt", format=[width + 2*margin, height + 2*margin])
pdf.add_page()
pdf.image(imagePath, margin, margin)
destination = os.path.splitext(imagePath)[0]
pdf.output(destination + ".pdf", "F")
回答by Giovanni G. PY
Some changes to make a pdf from the dir where the files are
从文件所在的目录制作 pdf 的一些更改
I take the code and made some slight change to make it useable as it is.
我接受了代码并进行了一些细微的更改,以使其可以按原样使用。
from fpdf import FPDF
from PIL import Image
import os # I added this and the code at the end
def makePdf(pdfFileName, listPages, dir=''):
if (dir):
dir += "/"
cover = Image.open(dir + str(listPages[0]))
width, height = cover.size
pdf = FPDF(unit="pt", format=[width, height])
for page in listPages:
pdf.add_page()
pdf.image(dir + str(page), 0, 0)
pdf.output(dir + pdfFileName + ".pdf", "F")
# this is what I added
x = [f for f in os.listdir() if f.endswith(".jpg")]
y = len(x)
makePdf("file", x)
回答by Syed Shamikh Shabbir
If you use Python 3, you can use the python module img2pdf
如果使用 Python 3,则可以使用 python 模块img2pdf
install it using pip3 install img2pdf
and then you can use it in a script
using import img2pdf
使用安装它pip3 install img2pdf
然后你可以在脚本中使用它import img2pdf
sample code
示例代码
import os
import img2pdf
with open("output.pdf", "wb") as f:
f.write(img2pdf.convert([i for i in os.listdir('path/to/imageDir') if i.endswith(".jpg")]))
回答by Valeriy Ivanov
I had the same problem, so I created a python function to unite multiple pictures in one pdf. The code (available from my github page, uses reportlab
, and is based on answers from the following links:
我遇到了同样的问题,所以我创建了一个 python 函数来将多张图片合并到一个 pdf 中。代码(可从我的 github 页面获得,使用reportlab
,并且基于以下链接中的答案:
- Create PDF from a list of images
- Combining multiple pngs in a single pdf in python
- png images to one pdf in python
- How can I convert all JPG files in a folder to PDFs and combine them?
- https://www.blog.pythonlibrary.org/2012/01/07/reportlab-converting-hundreds-of-images-into-pdfs/
- 从图像列表创建 PDF
- 在python中将多个png组合在一个pdf中
- 在python中将png图像转换为一个pdf
- 如何将文件夹中的所有 JPG 文件转换为 PDF 并合并它们?
- https://www.blog.pythonlibrary.org/2012/01/07/reportlab-converting-hundreds-of-images-into-pdfs/
Here is example of how to unite images into pdf:
以下是如何将图像合并为 pdf 的示例:
We have folder "D:\pictures" with pictures of types png and jpg, and we want to create file pdf_with_pictures.pdf out of them and save it in the same folder.
我们有文件夹“D:\pictures”,其中包含 png 和 jpg 类型的图片,我们想从中创建文件 pdf_with_pictures.pdf 并将其保存在同一文件夹中。
outputPdfName = "pdf_with_pictures"
pathToSavePdfTo = "D:\pictures"
pathToPictures = "D:\pictures"
splitType = "none"
numberOfEntitiesInOnePdf = 1
listWithImagesExtensions = ["png", "jpg"]
picturesAreInRootFolder = True
nameOfPart = "volume"
unite_pictures_into_pdf(outputPdfName, pathToSavePdfTo, pathToPictures, splitType, numberOfEntitiesInOnePdf, listWithImagesExtensions, picturesAreInRootFolder, nameOfPart)
回答by ilovecomputer
The best method to convert multiple images to PDF I have tried so far is to use PIL
purely. It's quite simple yet powerful:
到目前为止,我尝试过的将多个图像转换为 PDF 的最佳方法是PIL
纯粹使用。它非常简单但功能强大:
from PIL import Image
im1 = Image.open("/Users/apple/Desktop/bbd.jpg")
im2 = Image.open("/Users/apple/Desktop/bbd1.jpg")
im3 = Image.open("/Users/apple/Desktop/bbd2.jpg")
im_list = [im2,im3]
pdf1_filename = "/Users/apple/Desktop/bbd1.pdf"
im1.save(pdf1_filename, "PDF" ,resolution=100.0, save_all=True, append_images=im_list)
Just set save_all
to True
and append_images
to the list of images which you want to add.
只需将和设置save_all
为要添加的图像列表。True
append_images
You might encounter the AttributeError: 'JpegImageFile' object has no attribute 'encoderinfo'
. The solution is here Error while saving multiple JPEGs as a multi-page PDF
您可能会遇到AttributeError: 'JpegImageFile' object has no attribute 'encoderinfo'
. 解决方案在这里将多个 JPEG 保存为多页 PDF 时出错
Note:Install the newest PIL
to make sure save_all
argument is available for PDF.
注意:安装最新版本PIL
以确保save_all
参数可用于 PDF。
回答by user7384403
**** Convert images files to pdf file.****
from os import listdir
from fpdf import FPDF
path = "/home/bunny/images/" # get the path of images
imagelist = listdir(path) # get list of all images
pdf = FPDF('P','mm','A4') # create an A4-size pdf document
x,y,w,h = 0,0,200,250
for image in imagelist:
pdf.add_page()
pdf.image(path+image,x,y,w,h)
pdf.output("images.pdf","F")
回答by Vaibhav Singh
I know the question has been answered but one more way to solve this is using the pillow library. To convert a whole directory of images:
我知道问题已得到解答,但解决此问题的另一种方法是使用枕头库。要转换整个图像目录:
from PIL import Image
import os
def makePdf(imageDir, SaveToDir):
'''
imageDir: Directory of your images
SaveToDir: Location Directory for your pdfs
'''
os.chdir(imageDir)
try:
for j in os.listdir(os.getcwd()):
os.chdir(imageDir)
fname, fext = os.path.splitext(j)
newfilename = fname + ".pdf"
im = Image.open(fname + fext)
if im.mode == "RGBA":
im = im.convert("RGB")
os.chdir(SaveToDir)
if not os.path.exists(newfilename):
im.save(newfilename, "PDF", resolution=100.0)
except Exception as e:
print(e)
imageDir = r'____' # your imagedirectory path
SaveToDir = r'____' # diretory in which you want to save the pdfs
makePdf(imageDir, SaveToDir)
For using it on an single image:
在单个图像上使用它:
From PIL import Image
import os
filename = r"/Desktop/document/dog.png"
im = Image.open(filename)
if im.mode == "RGBA":
im = im.convert("RGB")
new_filename = r"/Desktop/document/dog.pdf"
if not os.path.exists(new_filename):
im.save(new_filename,"PDF",resolution=100.0)
回答by svinec
It's not a truly new answer, but - when using img2pdf the page size didn't come out right. So here's what I did to use the image size, I hope it finds someone well:
这不是一个真正的新答案,但是 - 使用 img2pdf 时,页面大小不正确。所以这是我使用图像大小所做的工作,我希望它能很好地找到某人:
assuming 1) all images are the same size, 2) placing one image per page, 3) image fills the whole page
假设 1) 所有图像大小相同,2) 每页放置一张图像,3) 图像填满整个页面
from PIL import Image
import img2pdf
with open( 'output.pdf', 'wb' ) as f:
img = Image.open( '1.jpg' )
my_layout_fun = img2pdf.get_layout_fun(
pagesize = ( img2pdf.px_to_pt( img.width, 96 ), img2pdf.px_to_pt( img.height, 96 ) ), # this is where image size is used; 96 is dpi value
fit = img2pdf.FitMode.into # I didn't have to specify this, but just in case...
)
f.write( img2pdf.convert( [ '1.jpg', '2.jpg', '3.jpg' ], layout_fun = my_layout_fun ))