Print the PDF file and delete the file when printing is complete.

I have a Python application that will execute repeatedly. It saves the PDF as a file, and then prints it. When printing ends, it deletes the file.

My current solution (for the print and delete part):

win32api.ShellExecute(0, "print", file_path, None,  ".",  0)
time.sleep(10)
os.remove(self.options.dest_name)

time.sleep(10)- This is a trick to give the printing process time to start before deleting the file. Without it, Acrobat Reader opens (it still opens) and warns that it cannot find the file. This is because file deletion has already occurred.

question :

  • How can I do this without this unreliable trick? It would be best to have a handler for the printing process and get information on the print status from it: I wait for it to report this, and I will delete the file.

  • it would be even better if Acrobat Reader does not open, but this is not a big problem.

EDIT: I tried switching to Foxit Reader as the default PDF reader, and now it doesn't open when I don't want to.;)

OTHER POSSIBLE SOLUTIONS : Cylically check if the file is accessible (not used by another process), and when it is available, delete it again. How can I do this in Python?

+3
source share
4 answers

- , ( @Lennart ):

Ghostscript

GSview ( gsprint.exe)

:

file_path = "C:\\temp\\test.pdf"
p = subprocess.Popen(["C:\\Ghostgum\\gsview\\gsprint.exe", "-printer", printer_name, "-colour",  file_path],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate() # waits for the gs process to end
os.remove(file_path) # now the file can be removed

Acrobat , ... : GS.

: gsprint

+4

tempfile .

import tempfile
file_name = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)

, script Window .

+2

Adobe acrobat (, , - ) "/t", , . , , .

:

>>> import subprocess
# You will have to figure out where your Acrobate reader is located, can be found in the registry:
>>> acrobatexe = "C:\Program Files\Adobe\Acrobat 4.0\Reader\AcroRd32.exe"  
>>> subprocess.call([acrobatexe, "/t", tempfilename, "My Windows Printer Name"])
>>> os.unlink(tempfilename)

- .

If you do not want to open acrobat, there is open source software that will output pdf files from the command line. You can include it in your software.

+1
source

Why not use os.systemone that will wait for the process to complete?

0
source

Source: https://habr.com/ru/post/1780844/


All Articles