I have written a python script that takes RTF files that my system is creating and converting it in to DOCX format. I accomplished this with pywin32 library. By this library I'm able to open Word and save as DOCX.
def ConvertRtfToDocx(path, file):
word = win32com.client.Dispatch("Word.Application")
wdFormatDocumentDefault = 16
wdHeaderFooterPrimary = 1
doc = word.Documents.Open(path + file)
for pic in doc.InlineShapes:
try:
pic.LinkFormat.SavePictureWithDocument = True
except:
pass
for hPic in doc.sections(1).headers(wdHeaderFooterPrimary).Range.InlineShapes:
try:
hPic.LinkFormat.SavePictureWithDocument = True
except:
pass
doc.SaveAs(str(path + file.split(".")[0] + ".docx"), FileFormat=wdFormatDocumentDefault)
doc.Close()
word.Quit()
This have to run on demand, as its scanning the directory and converting it as soon it finds it. Long story short, I was able to run it successfully with simple cmd. However, when I ran this as a service (NSSM) or "run as a batch job" its fails. I'm assuming its because the python has no display to open the Word to...
My operation system is Windows Server.
I will be appreciated if someone could help me with this task. One more note, it will be great if the solution will be use as less third-party software as it possible.
Its turnout that the problem wasn't about the virtual display. The problem is that Microsoft does not allow use of Office applications in batch mode, by default. That why in 2008 they change the windows in the way that just logon regular users can make a use of Office and Office objects. But there are a few ways you can overcome this obstacle.
The easiest way is to create these paths –
Windows Server x64
C:\Windows\SysWOW64\config\systemprofile\Desktop
Windows Server x86
C:\Windows\System32\config\systemprofile\Desktop
This way you are creating the “environment” for the system user (Admin) which is the executor of batch jobs. And you can run it as a batch job via Task Schedular, windows services etc.
But if it doesn't work for you this way, I recommend you read those links – Microsoft explanation about interaction with MS objects in a batch- https://www.betaarchive.com/wiki/index.php/Microsoft_KB_Archive/257757 Forum about this issue – https://social.msdn.microsoft.com/Forums/en-US/b81a3c4e-62db-488b-af06-44421818ef91/excel-2007-automation-on-top-of-a-windows-server-2008-x64?forum=innovateonoffice
You can also use my repository on Github - https://github.com/TechNapoleon/RTF_TO_DOCX_CONVERTOR