我正在使用Python 3.8和docx2pdf 0.1.7。多年来,我一直在尝试在我的脚本中添加一些内容,将 docx 转换为 pdf。我尝试了各种各样的方法,但到目前为止没有任何效果。
有一个名为 docx2pdf 的模块,它应该转换我刚刚创建的文件,但它似乎不起作用,我不明白为什么会这样。我尝试在我的脚本中运行它,但我也尝试将它作为子进程运行,但都不起作用。该模块的文档位于here。
我认为这是一个非常未知的模块,因为我在互联网上找不到任何答案,所以我希望有人知道如何解决这个问题。
这是我正在使用的代码:
from docx import Document
from docx.shared import Pt
from tkinter import *
from docx2pdf import convert
root = Tk()
# Then some irrelevant code for this question
def updater()
doc = Document('./Contract.docx')
# Then some code which updates the doc according to the tkinter Entry input
# Save it according to some of the input from the GUI
doc.save('/Users/Jem/Documents/Huurovereenkomsten/Specifiek/{}/contract{}.docx'.format(nospaceadres,
naamhuurder.get()))
# It all works fine until here
convert('/Users/Jem/Documents/Huurovereenkomsten/Specifiek/{}/contract{}.docx'.format(nospaceadres,
naamhuurder.get())) # This should convert it to a pdf with the same name in the same folder
# Some Tkinter GUI code which is also irrelevant for this question
root.mainloop()
但首先,它给了我这个:
0%| | 0/1 [00:02<?, ?it/s]
然后它在我的 MacBook 上打开 MS Word 并告诉我它需要许可证/权限才能打开 docx。然后我必须选择该文档,这将授予它打开它的权限。之后,它打开 docx 但没有任何反应。
之后,它给了我这个:
{'input': '/Users/Jem/Documents/Huurovereenkomsten/Specifiek/slotlaan73/contractabc.docx', 'output': '/Users/Jem/Documents/Huurovereenkomsten/Specifiek/slotlaan73/contractabc.pdf', 'result': 'error', 'error': 'Error: Er heeft zich een fout voorgedaan.'}
“Er heeft zich een fout voorgedaan。”荷兰语的意思是:发生了错误。
有谁知道为什么会发生这种情况,或者我可以做些什么来让它工作,以便将 docx 转换为 pdf?
尝试此代码,如果发生任何错误,请发布错误的屏幕截图......我们将尝试解决
import tkinter as to
import tkinter.ttk as ttk
from tkinter.filedialog import askopenfile
from tkinter.messagebox import showinfo
from docx2pdf import convert
win = tk.Tk()
win.title("Word To PDF Converter")
def openfile():
file = askopenfile(filetypes = [('Word Files','*.docx')])
print(file)
convert(file.name)
showinfo("Done","File Successfully Converted")
label = tk.Label(win,text='Choose File: ')
label.grid(row=0,column=0,padx=5,pady=5)
button = ttk.Button(win,text='Select',width=30,command=openfile)
button.grid(row=0,column=1,padx=5,pady=5)
win.mainloop()
您尝试转换时是否打开了 .docx 文件?
我遇到了完全相同的问题(0%和权限错误,只是没有得到荷兰语错误(ookal ben ik ook nederlands)),但就在我尝试转换文档之前,我保存了,更重要的是,打开了单词带有我的代码的文档。
当我更改代码,使其在将 .docx 文件转换为 .pdf 文件之前不会打开 .docx 文件时,它确实可以正常工作。
我认为由于某种原因 docx2pdf 尝试打开 .docx 文件。因此,当您尝试转换并已打开 .docx 文件时,Word 会向您显示权限警告/错误。
希望这对您有帮助。