0

I'm completely stuck trying to figure out why this code isn't working. I'm ultimately trying to print to the printer named "Label Printer'. I can't seem to figure out why I cannot do it in Python, I've tested it out of Python and it's definitely connected and working.

Does it need to be defined differently or something? Or is there a different way to connect?

Any advice on connecting to a printer via python is greatly appreciated.

My full code is below - this is what I want to update:

import gspread
from oauth2client.service_account import ServiceAccountCredentials
import win32print
import tkinter as tk

# Authenticate and open the Google Sheet
creds = ServiceAccountCredentials.from_json_keyfile_name('creds.json', [
                                                         'https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'])
client = gspread.authorize(creds)
sheet = client.open_by_key(
    '1eRO-30eIZamB5sjBp-Mz2QMKCfGxV037MQO8nS7G7AI').worksheet('Label')


class App(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.master.title('Porter\'s Label Printer')
        self.master.geometry('400x300')  # Set the window size
        self.counter = 0
        self.total_labels = int(sheet.acell('F2').value)
        self.create_widgets()
        self.update_counter()

    def create_widgets(self):
        self.print_button = tk.Button(self.master, text='Print Labels', command=self.print_labels, font=(
            'Arial', 24), bg='lightblue', padx=40, pady=40)
        self.print_button.pack(fill=tk.BOTH, expand=True)

        self.counter_label = tk.Label(self.master, text='0 of {} labels printed'.format(
            self.total_labels), font=('Arial', 18))
        self.counter_label.pack(pady=20)

        self.refresh_button = tk.Button(self.master, text='Refresh', command=self.refresh_labels, font=(
            'Arial', 14), bg='lightgrey', padx=20, pady=10)
        self.refresh_button.pack(pady=20)

    def print_labels(self):
        for i in range(self.total_labels):
            win32print.SetDefaultPrinter('Label Printer')
            print_label_data = sheet.cell(sheet.find(
                'Label').row, sheet.find('Label').col).value
            print(print_label_data)
            self.counter += 1
            self.update_counter()

    def refresh_labels(self):
        try:
            self.total_labels = int(sheet.acell('F2').value)
            self.counter = 0
            self.update_counter()
            self.print_button.config(state=tk.NORMAL)
            self.counter_label.config(fg='black')
        except ValueError:
            print('Error: could not convert F2 value to an integer')
            self.total_labels = 0
            self.counter_label.config(
                text='Invalid number of labels!', fg='red')
            self.print_button.config(state=tk.DISABLED)

    def update_counter(self):
        if self.counter == self.total_labels:
            self.counter_label.config(
                text='All documents printed!', fg='green')
            self.print_button.config(state=tk.DISABLED)
        else:
            self.counter_label.config(text='{} of {} labels printed'.format(
                self.counter, self.total_labels))


# Authenticate and open the Google Sheet
creds = ServiceAccountCredentials.from_json_keyfile_name('creds.json', [
                                                         'https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'])
client = gspread.authorize(creds)
sheet = client.open_by_key(
    '1eRO-30eIZamB5sjBp-Mz2QMKCfGxV037MQO8nS7G7AI').worksheet('Label')

# Create a GUI window
root = tk.Tk()
app = App(master=root)

# Run the GUI
app.mainloop()

I've also tried a much more basic script just to print, but can't get this working either:

import win32print

# Set the IP address of the printer
printer_ip = '192.168.1.10'

# Create a printer handle
printer_handle = win32print.OpenPrinter(fr"\\{printer_ip}\ZDesigner GK420d")

# Get the default printer settings
default_printer_settings = win32print.GetPrinter(printer_handle, 2)

# Start a print job
job_info = ('Test Print', None, default_printer_settings, None)
job_id = win32print.StartDocPrinter(printer_handle, 1, job_info)

# Send the test page to the printer
win32print.StartPagePrinter(printer_handle)
win32print.WritePrinter(printer_handle, b'test')
win32print.EndPagePrinter(printer_handle)

# End the print job
win32print.EndDocPrinter(printer_handle)

# Close the printer handle
win32print.ClosePrinter(printer_handle)

I've tried connecting the printer via IP, but it can't be found. I retrieved all of the IP addresses from command prompt, but when it was plugged into the computer and when unplugged the list didn't change - I dont think it's being recognized. I can't get the IP from printer properties either - the port tab doesn't have them.

Anthony Madle
  • 371
  • 1
  • 10
  • Post a [mre] and debugging details. Why did you post the GUI code? Anyway you must have seen an exception when you call ```StartDocPrinter()```. See [the reference](https://mhammond.github.io/pywin32/win32print__StartDocPrinter_meth.html). – relent95 Mar 10 '23 at 05:35
  • sorry - i'm new to this and didn't think to remove GUI; going to keep playing with things, there was no error at all that showed, just simply nothing happened – Anthony Madle Mar 11 '23 at 21:16
  • 1
    The ```job_info``` should be a tuple of ```(docName, outputFile, dataType)``` such as ```("name", None, "RAW")```. See [this question](https://stackoverflow.com/questions/14506717/python-win32print-not-printing). – relent95 Mar 12 '23 at 01:13
  • This is helpful. I ordered a new printer in the spare time to continue testing. thank you very much – Anthony Madle Mar 13 '23 at 02:26

0 Answers0