Python 3库:将任何图像合并到PDF中

5
在Python 3中,我有一个包含各种格式(pdf、png、jpg、gif)图片的列表,并将它们合并成一个多页PDF文件。
使用PyPDF2可以合并PDF文件。但是,它不支持png、jpg等格式。这在这里被很好地介绍了:合并PDF文件 使用img2pdf,可将png、jpg等图像类型转换为PDF并合并。然而,它不支持输入PDF文件。这在这里被讨论:从图像列表创建PDF 因此,由于我的输入可能包括PDF、PNG、JPG格式,我需要像这样处理它:
from PyPDF2 import PdfFileMerger
import img2pdf

if not ext == 'pdf':
    with open("output.pdf", "wb") as f:
        f.write(img2pdf.convert(images))
else:
    merger = PdfFileMerger()
    for pdf in images:    
        merger.append(pdf)
    merger.write("output.pdf")

问题是:在将包括PDF在内的图像列表合并为一个PDF时,我是否需要这两个库?换句话说,是否有一个库可以将任何类型的图像作为输入(包括PDF),并将它们合并为一个PDF?
1个回答

1
我知道这个问题已经问了很久,但是我想分享一下我找到的答案,以防将来有其他人遇到同样的问题。 PyMuPDF模块提供了与PyPDF2模块类似的功能,但有一些PyPDF2没有的特性,包括这个。 根据PyMuPDF的文档,这里有一段代码可以解决这个问题。它使用了PySimpleGUI模块来提供用户界面,但如果你想的话,可以将其移除。
import os, fitz
import PySimpleGUI as psg  # for showing a progress bar
doc = fitz.open()  # PDF with the pictures
imgdir = "path-to-picture-directory"  # where the pics are
imglist = os.listdir(imgdir)  # list of them
imgcount = len(imglist)  # pic count

for i, f in enumerate(imglist):
    img = fitz.open(os.path.join(imgdir, f))  # open pic as document
    rect = img[0].rect  # pic dimension
    pdfbytes = img.convert_to_pdf()  # make a PDF stream
    img.close()  # no longer needed
    imgPDF = fitz.open("pdf", pdfbytes)  # open stream as PDF
    page = doc.new_page(width = rect.width,  # new page with ...
                   height = rect.height)  
# pic dimension
     page.show_pdf_page(rect, imgPDF, 0)  
# image fills the page
    psg.EasyProgressMeter("Import Images",  # show our progress
    i+1, imgcount)

 doc.save("all-my-pics.pdf")

你可以在模块的文档网站上找到这段代码以及更多关于PyMuPDF的信息,网址在这里: https://pymupdf.readthedocs.io/en/latest/recipes-images.html#how-to-make-one-pdf-of-all-your-pictures-or-files 希望这对你或将来遇到这个问题的人有所帮助!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接