Warm tip: This article is reproduced from serverfault.com, please click

python-从图像列表创建PDF

(python - Create PDF from a list of images)

发布于 2014-12-06 02:04:23

是否有使用Python从图像文件列表中创建PDF的实用方法?

在Perl中,我知道该模块有了它,我可以只用3行创建一个PDF:

use PDF::FromImage;
...
my $pdf = PDF::FromImage->new;
$pdf->load_images(@allPagesDir);
$pdf->write_file($bookName . '.pdf');

我需要用Python做类似的事情。我知道pyPdf模块,但是我想要一些简单的东西。

@编辑

如果你是通过Google来的,则代码如下:

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")
Questioner
macabeus
Viewed
12
105k 2016-08-11 21:18:47

为Python安装FPDF

pip install fpdf

现在,你可以使用相同的逻辑:

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

你可以在教程页面官方文档中找到更多信息