I have some reports in Access format and I want to generate PDF of these reports from Python script.
I read a lot of questions and answers about how to do it and came up with this simple script.
My code is:
import win32com.client as win
import os
access = win.Dispatch("Access.Application")
db = access.OpenCurrentDatabase(filename)
access.DoCmd.OpenReport(report_name,2)
access.DoCmd.OutputTo(3, report_name, r'PDF Format (*.pdf)','c:/temp/test.pdf' )
access.DoCmd.CloseDatabase
access.Quit()
access=None
Executing the script first time gives this error (translate for me in English):
pywintypes.com_error: (-2147352567, 'An exception occurred.', (0, None, ' Cannot execute this action now.', None, -1, -2146825802), None)
And file Access is open.
The second time I execute, it says The database is already open.
When I close the Access and execute it gives the first error again.
UPDATE: Now I change my code for closing database while script is executing and is the second time I executed, and then the scripts works fine.
import win32com.client as win
import os
import time
def file_open(file_name):
if os.path.exists(file_name):
try:
os.rename(file_name, file_name) #can't rename an open file so an error will be thrown
return False
except:
print("File Open "+file_name)
time.sleep(2)
file_open(file_name)
return True
else:
return False
raise NameError
access = win.Dispatch("Access.Application")
file_open(filename)
db = access.OpenCurrentDatabase(filename)
access.DoCmd.OpenReport(report_name,2)
if os.path.isfile('c:/temp/test.pdf'):
os.remove('c:/temp/test.pdf')
access.DoCmd.OutputTo(3, report_name, r'PDF Format (*.pdf)','c:/temp/test.pdf' )
access.DoCmd.CloseDatabase
access.Quit()
access=None
After this correct execution, if I executed another time I have the first error. I execute for second time and then works fine again.
Finally I find this solution. It's not better, but it works. If someone have a better solution please let me now.
The solution is kill MSACCESS process in windows.
This is my code:
import win32com.client as win
import os
access = win.Dispatch("Access.Application")
db = access.OpenCurrentDatabase(filename)
access.DoCmd.OpenReport(report_name,2)
if os.path.isfile('c:/temp/test.pdf'): # Delete previous PDF
os.remove('c:/temp/test.pdf')
access.DoCmd.OutputTo(3, report_name, r'PDF Format (*.pdf)','c:/temp/test.pdf' )
access.DoCmd.CloseDatabase
os.system("taskkill /im MSACCESS.exe") # Kill process in wondows