Automate printing of files within a folder

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

I was searching in Python but I was able to basically 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?

Author: jsbueno, 2018-03-02

1 answers

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 that is in that answer for windows ( http://timgolden.me.uk/python/win32_how_do_i/print.html ) has, in the last example, how to print a PDF file in Windows directly from the Python:

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

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

If the rest of your program is ok, that might 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 way I would try there is is to install ghostview - http://pages.cs.wisc.edu / ~ ghost / - then experiment and see the documentation until you find a way to print with ghostview from a command line-and then use the Python module subprocess to call ghostview with the command line to print each file.

(a tip on the part: avoid using os.chdir and wait for things to work afterwards - ideally, always concatenate the folder name to the file name before each operation with files: in scripts small ones don't have that much of a problem - but on larger systems the "current work dir" is global for the application, across all threads and is very unreliable. ) (If pathlib doesn't work because of your Python version, use os.join.path above)

Another cool tip there: on Windows, terminal applications are extremely uncomfortable. Python already comes with tools to create graphical applications that are very simple to use - what really gives work is to build an application more sophisticated. But in this case, you only need one folder, and keep monitoring it to see if more files appear - if so, shoot the print. Create the entire app I can't - but try it there, instead of input use this:

from tkinter import filedialog

loc = filedialog.askdirectory()

You can put the loop that checks files in your script into a function, and call that function with the after method from your window every two seconds, for example - 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()
 2
Author: jsbueno, 2018-03-02 13:12:55