Skip to content

Instantly share code, notes, and snippets.

@Dogers
Created December 10, 2018 11:39
Show Gist options
  • Save Dogers/d60a1b25f9b11bdfc7c54c2cf020466c to your computer and use it in GitHub Desktop.
Save Dogers/d60a1b25f9b11bdfc7c54c2cf020466c to your computer and use it in GitHub Desktop.
Send a file to Windows printer in RAW format
import win32print
import sys
from pathlib import Path
# Python 3 only..
if sys.version_info[0] < 3:
raise Exception("Python 3 or a more recent version is required.")
printers = win32print.EnumPrinters(4)
printercount = 0
for x in printers:
print(printercount, "-", x[2])
printercount += 1
chosenprinter = int(input("Printer number? "))
chosenfile = Path()
while not chosenfile.is_file():
filename = input("Enter PDF file path: ")
chosenfile = Path(filename)
myprinter = win32print.OpenPrinter(printers[chosenprinter][2])
printjob = win32print.StartDocPrinter(
myprinter, 1, ("Python test RAW print", None, "raw"))
with open(chosenfile, mode='rb') as file:
buf = file.read()
bytesprinted = win32print.WritePrinter(myprinter, buf)
win32print.EndDocPrinter(myprinter)
win32print.ClosePrinter(myprinter)
@lmbruguera
Copy link

thanks, this code was very helpful
I was with some trouble with win32shellexecute so I changed for this solution win32print methods and worked
thanks again!

@oshimamasara
Copy link

Thank you for the helpful program.
I want to print in A6 size.
I've tried many things, but it doesn't work.
If you know how to print in A6 size, please let me know.
Thank you.

printer_name = 'iR-ADV C3520 III'

PRINTER_DEFAULTS = {"DesiredAccess":win32print.PRINTER_ALL_ACCESS}
pHandle = win32print.OpenPrinter(printer_name, PRINTER_DEFAULTS)

properties = win32print.GetPrinter(pHandle, 2)
pDevModeObj = properties["pDevMode"]
automaticTray = 7

page_size = win32con.DMPAPER_A6
orientation = win32con.DMORIENT_PORTRAIT
pDevModeObj.DefaultSource = automaticTray
pDevModeObj.PaperSize = page_size
pDevModeObj.Orientation = orientation
properties["pDevMode"]=pDevModeObj
win32print.SetPrinter(pHandle,2,properties,0)

printjob = win32print.StartDocPrinter(
    pHandle, 1, ("Python test RAW print", None, "raw"))

with open(chosenfile, mode='rb') as file:
    buf = file.read()

win32print.EndDocPrinter(pHandle)
win32print.ClosePrinter(pHandle)

Printed in A4 size..

@Dogers
Copy link
Author

Dogers commented Feb 15, 2024

I've not tried, but unless the source document itself is A6, I don't believe you can? The raw option should simply be sending the document direct to the printer, as-is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment