Automate printing of files within a folder

1

I need to make any file that is in the folder, example c://imprimir , printed automatically, checks to see if it has something and sends it to the default printer .

I've been researching in Python but I've basically been able to access the folder and list and count each file that is within 1 to 1.

import os
import time
import glob

try:
    #Passa o caminho onde estão os arquivos pdf
    loc = input('Localizacao: ')

    #localizar pasta
    floc = loc.replace("'\'","'/'")

    #nav até caminho informado
    os.chdir(floc)

    x = 0

    #Verifica todos arquivos .pdf que tem na pasta
    for file in glob.glob('*.pdf'):
        if(file != ''):
            os.startfile(file, 'print')
            print('Imprimindo arquivo.. ' + str(file))
            x += 1
            time.sleep(2)

    print('Arquivos impressos: ' + str(x))

except Exception as a:
    print(a)

@Result:

=============== RESTART: C:/Users/willian/Desktop/imprimir.py ===============
Localizacao: C:/imprimir
Imprimindo arquivo.. teste - Cópia (2).pdf
Imprimindo arquivo.. teste - Cópia.pdf
Imprimindo arquivo.. teste.pdf
Nenhum arquivo para imprimir 3
>>> 
=============== RESTART: C:/Users/willian/Desktop/imprimir.py ===============
Localizacao: C:/imprimir
Arquivos impressos: 0
>>> 

How could I print and if possible print and move or delete the file?

    
asked by anonymous 02.03.2018 / 13:05

1 answer

2

Your files are already in PDF - it's the big difference to the answer in How to print a txt file in Python . but it gives a good foundation of what is involved in printing and why Python or other languages do not have a direct command to "print".

But the link in that answer for windows ( link ) has, in the last example, how print a PDF file in Windows direct from Python:

You should install win32api (it's in Pypi with the name pywin32 - pip install pywin32 should be enough). And then the call in the last line in the last example in the link above, should be enough to trigger the print itself:

win32api.ShellExecute (0, "print", pdf_file_name, None, ".", 0)

If the rest of your program is ok, this could be enough here:

import os
import win32api
import pathlib

...     
loc = input('Localizacao: ')

#localizar pasta
floc = pathlib.Path(loc)

#Verifica todos arquivos .pdf que tem na pasta
try:
    os.mkdir(floc/"impressos")
except OSError:
    # pasta já existe
    pass 
for file in glob.glob(floc/'*.pdf'):
    if(file != ''):
        os.startfile(file, 'print')
        print('Imprimindo arquivo.. ' + str(file))
        win32api.ShellExecute (0, "print", os.path.join(floc, file), None, ".", 0)
        x += 1
        time.sleep(2)
        os.rename(floc/file, floc/"impressos"/file)

If win32api to print fails, the path I would try there is is to install ghostview - link - then try and see the documentation until you find a way to print ghostview from a command line - and then use the subprocess module from Python to call ghostview with the command line to print each file.

(a tip aside: avoid using os.chdir and wait for things to work later - the ideal is to always concatenate the folder name to the file name before each file operation: in small scripts there is not much problem - but on larger systems the "current work dir" is global for the application, on all threads and is very unreliable.) (If pathlib does not work because of your version of Python, use the.join.path above)

Another cool tip there: In Windows terminal applications are extremely uncomfortable. Python already comes with tools to create graphical applications that are very simple to use - what really works is building a more sophisticated application. But in that case, you only need one folder, and keep monitoring it to see if more files appear - if so, fire the printout. Creating the whole app I can not - but try it instead of the input use this:

from tkinter import filedialog

loc = filedialog.askdirectory()

You can either by the loop that checks files in your script in a function, and call that function with the after method of your window every two seconds, for example - in that way any file placed there will be printed.

Although most tutorials create a class that inherits from tkinter.frame, this is not necessary: your program can be in a normalized function and simply call tkinter.Tk () to have a window.

The structure would look more or less

<importacoes>

pasta = ""

def principal():
    global pasta, janela
    janela = Tkinter.Tk()
    # criar Labels para conter o nome da pasta, mensagens de impressao
    ...
    botao = tkinter.Button(janela, text="Mudar pasta...", command="seleciona_pasta")
    # chama a funcao imprime em 2 segundos:
    janela.after(2000, imprime)

def imprime():
    # basicamente o mesmo código que está na versão de terminal
    # sem o input - a pasta vem na variável global "pasta"
    ...
    # se chama de volta (opcional)
    janela.after(2000, imprime)

def mudar_pasta():
    global pasta
    pasta = filedialog.askdirectory()
    # atualizar label com o nome da pasta atual. 

principal()
    
02.03.2018 / 13:37