简体   繁体   English

使用 python 将 tif 文件转换为 pdf

[英]Converting tif files to pdf with python

Hi I have a folder with multiple.tif files that I'm trying to convert to individual pdf's.嗨,我有一个包含多个.tif 文件的文件夹,我正在尝试将其转换为单个 pdf 文件。 I'm trying to use python as they are more than 3000. I was able to convert a single one but when implementing a code I found for multiples is giving me an error "No such file or directory:" This is the code I'm using, thanks in advance.我正在尝试使用 python,因为它们超过 3000。我能够转换一个,但是在实现我找到的多个代码时给我一个错误“没有这样的文件或目录:”这是我的代码我正在使用,在此先感谢。

from PIL import Image 
import os
directory = r'/Users/reynierDesktop/Drive/' 
for filename in os.listdir(directory): 
    if filename.endswith(".tif"): 
        prefix = filename.split(".tif")[0]
        im = Image.open(filename)
        im.save(prefix+'.pdf')  
    else: 
        continue

I was able to find something and it kind of works.我能够找到一些东西,它有点工作。 It converts the tif files to pdf, but if the tiff files has more than 1 page it only converts the first one.它将 tif 文件转换为 pdf,但如果 tiff 文件的页面超过 1 页,它只会转换第一个页面。 Any idea how to go around this?知道如何围绕这个 go 吗? Thanks.谢谢。

from PIL import Image
import os

def makePdf(imageDir, SaveToDir):
    os.chdir(imageDir)
    for j in os.listdir(os.getcwd()):
           os.chdir(imageDir)
           fname, fext= os.path.splitext(j)
           newfilename = fname + ".pdf"
           im = Image.open(fname + fext)
           os.chdir(SaveToDir)
           im.save(newfilename, "PDF", resolution = 100.0)


imageDir = r'my directory path'
SaveToDir = r'where to save them'
makePdf(imageDir, SaveToDir)

jonathan, your directory may be /Users/reynierDesktop/Drive/ but your filename is only something.tif (you can see this if you print out the filename) jonathan,你的目录可能是 /Users/reynierDesktop/Drive/ 但你的文件名只是 something.tif (如果你打印出文件名,你可以看到这个)

so when you Image.open(filename), you are looking for something.tif not /Users/reynierDesktop/Drive/something.tif所以当你 Image.open(filename) 时,你正在寻找 something.tif 而不是 /Users/reynierDesktop/Drive/something.tif

so one way around that would be to concat the directory with the filename when using Image.open or you could cd into /Users/reynierDesktop/Drive/ first and then just the filename will be found because you are in the correct directory.所以解决这个问题的一种方法是在使用 Image.open 时将目录与文件名连接起来,或者你可以先 cd 进入 /Users/reynierDesktop/Drive/ 然后只找到文件名,因为你在正确的目录中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM