Automate printing of files within a folder

Asked

Viewed 2,179 times

1

I need to make any file that is in the folder, example c://imprimir automatically printed, check if you have something and send it to standard printer.

I’ve been searching in Python but I was able to basically access the folder and list and count each file inside 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)

@Upshot:

=============== 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 to have the file printed and if possible print and move or delete?

  • Related, but not duplicated: https://answall.com/questions/65072/como-imprimir-um-arquivo-txt-em-python/65122#65122

  • @jsbueno in your case is about to open in the browser and the person has to give the command.. in this case it is not viable because this form I need will put a lot in the folder

1 answer

2

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

But the link that is in that reply to windows (http://timgolden.me.uk/python/win32_how_do_i/print.html) has, in the last example, how to print a PDF file on Windows directly from Python:

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

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

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

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 the win32api for printing fails, the way I would try there is to install ghostview - http://pages.cs.wisc.edu/~ghost/ - then try and see the documentation until you find a way to print with ghostview from a command line - and then use the module subprocess Python to call ghostview with the command line to print each file.

(a hint to share: avoid using the os.chdir and expect things to work later - the ideal is always to concatenate the folder name to the file name before each file operation: in small scripts there is not so much problem - but in 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 Python version, 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 quite simple to use - what really takes work is to build a more sophisticated application. But in this case, you only need one folder, and keep monitoring it to see if more files appear - if so, trigger the print. I can’t create the entire app - but try it there instead of input using it:

from tkinter import filedialog

loc = filedialog.askdirectory()

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

Although most tutorials create a class they inherit from Tkinter.frame, this is not necessary: your program may be in a normal function and simply call Tkinter. Tk() to have a window.

The structure would be 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()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.