Can we convert the docx file created by python-docx to pdf or there is any way to save as the docx file to pdf.
Thats a whole different story, not something this library deals with. See unoconv.
thanks for your reply
thanks for your comment is there any other way other than unoconv so that from code only i can convert the docx created by python-docx to pdf
That, I dont know.
I use the following function, which is reliant on PyWin32
def convert_to_pdf(doc):
try:
word = client.DispatchEx("Word.Application")
new_name = doc.replace(".docx", r".pdf")
worddoc = word.Documents.Open(doc)
worddoc.SaveAs(new_name, FileFormat = 17)
worddoc.Close()
except Exception, e:
return e
finally:
word.Quit()
thanks fstraw
i had one more question Brandon i am basically taking out text from a wysiwyg editor which contains images as well as text in it so I need to add those images with the text in there relative position in the docx created. Can you help me with this. the text may also contain some wysiwyg formulas also.
Any other module because pywin doesn't work in ubuntu
I upload the docx to Google Drive and download a PDF version. It's not perfect, but works for me, and can be done with the Google Python libraries
For conversion have look at pandoc https://pandoc.org/
@fstraw 's solution works well. Here's some more info:
Install pywin32 via:
> pip install pywin32You may need to refresh your session if using a script or notebook.
import win32com.client as client
def convert_to_pdf(filepath:str):
"""Save a pdf of a docx file."""
try:
word = client.DispatchEx("Word.Application")
target_path = filepath.replace(".docx", r".pdf")
word_doc = word.Documents.Open(filepath)
word_doc.SaveAs(target_path, FileFormat=17)
word_doc.Close()
except Exception as e:
raise e
finally:
word.Quit()
I've found this approach to preserve embedded images and styles from a .docx file (compared to pandoc).
@pylang , do you have a solution that is not based on win32com? Our MS macro has been disabled by the firm. cannot use anything based on win32com.
Most helpful comment
I use the following function, which is reliant on PyWin32