I am wondering how to close a pdf file once it has printed. I am using subprocess.popen to print the file but I need to physically close the acrobat application before it can go to the next file (as i believe the subprocess doesn't recognise that the process has already completed and is waiting for the user to close the application). I am running through a loop calling main when a file is found. See below.
def main(pdffile, printer_name):
# Set the command prompt code
cmd = '"{}" /N /T "{}" "{}"'.format(acrobat, pdffile, printer_name)
# print(cmd)
# Printing the pdf and waiting for process to finish before continuing with the rest of the script
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc.communicate('None')[0]
# Get File Name
filename = (os.path.basename(pdffile))
destination_folder = f'{destination_labels}' filename
# print(destination_folder)
# Move file once printed
shutil.move(pdffile,destination_folder)
Any help is appreciated.
CodePudding user response:
Rather than using subprocess
, I would recommend you to use the default open()
and close()
functions.
Here's a sample code:
from PyPDF2 import PDFFileReader
with open('document_path.PDF','rb') as file: #Automatically closes file when exited.
pdf_file = PDFFileReader(file)
first_page = pdf_file.getPage(0) # Get Page 1
print(first_page.extractText())
To install PyPDF2 simply run pip install pypdf2
in cmd
.
CodePudding user response:
For anyone wondering, the loop hole I used was os.startfile(acrobat)
, which pre launched the adobe application. This meant that when I opened a new instance of adobe using subprocess.popen
, once the file printed it would recognise the file as be completed and carry on with the rest of the script.