问题描述
我正在使用 Python 脚本将不同文件夹中的许多图像批量转换为单个 pdf(使用 https://pypi.org/project/img2pdf/):
import os
import subprocess
import img2pdf
from shutil import copyfile
def main():
folders = [name for name in os.listdir(".") if os.path.isdir(name)]
for f in folders:
files = [f for f in os.listdir(f)]
p = ""
for ffile in files:
p += f+'\\' + ffile + " "
os.system("py -m img2pdf *.pn* " + p + " --output " + f + "\combined.pdf")
if __name__ == '__main__':
main()
然而,尽管在 Windows 10 上通过 Powershell 运行命令,并且尽管使用了非常短的文件名,但当图像数量非常高(例如超过 600 个左右)时,Powershell 给了我错误“命令行太长"并且它不会创建 pdf。我知道有一个命令行字符串限制 (https://docs.microsoft.com/en-us/troubleshoot/windows-client/shell-experience/command-line-string-limitation),但我也知道对于 powershell 这个限制更高 (Powershell to avoid cmd 8191 character limit),我不知道如何修复脚本。我想问你是否可以帮助我修复脚本以避免违反字符限制。谢谢
PS:我在将脚本插入包含图像文件夹的父文件夹后使用脚本;然后在每个子文件夹中创建输出 pdf 文件。
解决方法
使用 img2pdf
库,您可以使用此脚本:
import img2pdf
import os
for r,_,f in os.walk("."):
imgs = []
for fname in f:
if fname.endswith(".jpg") or fname.endswith(".png"):
imgs.append(os.path.join(r,fname))
if len(imgs) > 0:
with open(r+"\output.pdf","wb") as f:
f.write(img2pdf.convert(imgs))