Fix silent printing and shorten printer display names

- Print directly via win32print API without opening PDF viewer
- Shorten printer names to 20 chars in dropdown (strip server prefix for network printers)
- Map display names back to full names for printing
- PDF backup saved silently without launching viewer
This commit is contained in:
2026-02-06 11:18:27 +02:00
parent 1cf4482914
commit b204ce38fc
2 changed files with 80 additions and 31 deletions

View File

@@ -249,38 +249,58 @@ def print_to_printer(printer_name, file_path):
return True
elif SYSTEM == "Windows":
# Windows: Use win32print API for reliable printing (supports UNC paths)
# Windows: Print directly without opening PDF viewer
try:
if WIN32_AVAILABLE:
import win32print
import win32api
# Set the target printer as default temporarily, then print
# This approach works reliably with both local and UNC printer paths
try:
old_default = win32print.GetDefaultPrinter()
except:
old_default = None
try:
win32print.SetDefaultPrinter(printer_name)
win32api.ShellExecute(0, "print", file_path, None, ".", 0)
print(f"Label sent to printer: {printer_name}")
finally:
# Restore original default printer
if old_default:
try:
win32print.SetDefaultPrinter(old_default)
except:
pass
return True
else:
# Fallback: Open with default printer
if file_path.endswith('.pdf'):
os.startfile(file_path, "print")
# Use SumatraPDF command-line or direct raw printing
# Try printing via subprocess to avoid opening a PDF viewer window
# Method: Use win32print raw API to send to printer silently
try:
hprinter = win32print.OpenPrinter(printer_name)
try:
# Start a print job
job_info = ("Label Print", None, "RAW")
hjob = win32print.StartDocPrinter(hprinter, 1, job_info)
win32print.StartPagePrinter(hprinter)
# Read PDF file and send to printer
with open(file_path, 'rb') as f:
pdf_data = f.read()
win32print.WritePrinter(hprinter, pdf_data)
win32print.EndPagePrinter(hprinter)
win32print.EndDocPrinter(hprinter)
print(f"Label sent to printer: {printer_name}")
finally:
win32print.ClosePrinter(hprinter)
return True
except Exception as raw_err:
print(f"Raw print failed ({raw_err}), trying ShellExecute silently...")
# Fallback: Use ShellExecute with printto (minimized, auto-closes)
try:
win32api.ShellExecute(
0, "printto", file_path,
f'"{printer_name}"', ".", 0
)
print(f"Label sent to printer: {printer_name}")
return True
except Exception as shell_err:
print(f"ShellExecute print failed: {shell_err}")
return True
else:
subprocess.run(['notepad', '/p', file_path], check=False)
print(f"Label sent to default printer")
# Non-PDF files: print silently with notepad
subprocess.run(['notepad', '/p', file_path],
check=False,
creationflags=subprocess.CREATE_NO_WINDOW)
print(f"Label sent to printer: {printer_name}")
return True
else:
print("win32print not available, PDF saved as backup only")
return True
except Exception as e:
print(f"Windows print error: {e}")