Python convert word tới PDF

folder = 'E:\\Code\\Quanlytailieu\\media\\documents\\upload'
pdf = "E:\\Code\\Quanlytailieu\\media\\documents\\pdf"
words = 'E:\\Code\\Quanlytailieu\\media\\documents\\word'

chdir(folder)


def con():
    try:
        word = client.DispatchEx("Word.Application")
        for files in listdir(getcwd()):
            if files.endswith(".docx"):
                new_name = files.replace(".docx", r".pdf")
                in_file = path.abspath(folder + "\\" + files)
                new_file = path.abspath(pdf + "\\" + new_name)
                doc = word.Documents.Open(in_file)
                print(strftime("%H:%M:%S"), " docx -> pdf ", path.relpath(new_file))
                chdir(pdf)
                doc.SaveAs(new_file, FileFormat=17)
                doc.Close()
                shutil.move(folder + "\\" + files, words + "\\" + files)
    # if files.endswith(".doc"):
    #     new_name = files.replace(".doc", r".pdf")
    #     in_file = path.abspath(folder + "\\" + files)
    #     new_file = path.abspath(pdf + "\\" + new_name)
    #     doc = word.Documents.Open(in_file)
    #     print(strftime("%H:%M:%S"), " doc  -> pdf ", path.relpath(new_file))
    #     chdir(pdf)
    #     doc.SaveAs(new_file, FileFormat=17)
    #     doc.Close()
    #     shutil.move(in_file, words + "\\" + files)
    #     chdir(folder)
    #     remove(files)

    except Exception as e:
        print("Exception: ", e)
    finally:
        word.Quit()

Em để ngoài hàm thì convert được nhưng để bên trong hàm thì biến word ở cuối cùng nó báo là: Local variable ‘word’ might be referenced before assigment. Làm thế nào để sửa đây ạ?

Đặt word lên trước try, có thể khai báo cho nó một giá trị null

1 Like
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?