[英]Python Convert all JPGS in a folder to PDF
I have code that converts all .jpgs in a folder to one PDF, but it is not working.我有将文件夹中的所有 .jpg 转换为一个 PDF 的代码,但它不起作用。 I believe it to be because of something with my directory being passed.
我相信这是因为我的目录被传递了。 The below is the code and my output.
下面是代码和我的输出。 Now it states that my PDF was written, but it doesn't display the directory.
现在它指出我的 PDF 已编写,但它不显示目录。
root = "C:\\Users\\Matthew\\Desktop\\Comics\\"
try:
n = 0
for dirpath, dirnames, filenames in os.walk(root):
PdfOutputFileName = os.path.basename(dirpath) + ".pdf"
c = canvas.Canvas(PdfOutputFileName)
if n > 0 :
for filename in filenames:
LowerCaseFileName = filename.lower()
if LowerCaseFileName.endswith(".jpg"):
print(filename)
filepath = os.path.join(dirpath, filename)
print(filepath)
im = ImageReader(filepath)
imagesize = im.getSize()
c.setPageSize(imagesize)
c.drawImage(filepath,0,0)
c.showPage()
c.save()
n = n + 1
print "PDF of Image directory created" + PdfOutputFileName
except:
print "Failed creating PDF"
The below is my output:以下是我的输出:
PDF of Image directory created.pdf
At start n
is 0
.开始时
n
是0
。
The os.walk
loop only runs once in this case (since there's probably only one directory to scan, and you get only one print
statement so that's the proof), providing filenames
and dirnames
as iterables, but you skip the iteration by testing n > 0
, so it does nothing.在这种情况下,
os.walk
循环只运行一次(因为可能只有一个目录要扫描,而您只得到一个print
语句,所以这就是证明),提供filenames
和dirnames
filenames
作为可迭代对象,但您通过测试n > 0
跳过迭代n > 0
,所以它什么都不做。
for dirpath, dirnames, filenames in os.walk(root):
PdfOutputFileName = os.path.basename(dirpath) + ".pdf"
c = canvas.Canvas(PdfOutputFileName)
if n > 0 :
My advice: get rid of the if n > 0
test.我的建议:摆脱
if n > 0
测试。
Have a look at img2pdf
for lossless conversion in Python:看看
img2pdf
在 Python 中的无损转换:
https://gitlab.mister-muffin.de/josch/img2pdf https://gitlab.mister-muffin.de/josch/img2pdf
Example CLI usage: CLI 用法示例:
img2pdf img1.png img2.jpg -o out.pdf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.