python win32ui and win32printer to set page size and printer printing

47 Views Asked by At

printing set it cant work,the code can printing out but size have not change,Exception capture does not show any prompts,i hope to get some help,and also i have a question,printing requires running the code with administrator privileges, If I package it into an exe, do I still need administrator rights for printing? I' ve looked around,However, the method found is c# or c++. The file printed only using win32printer shows an error and cannot be browsed, and the content is 0kb. Thanks in advance.

import win32con
import win32print
import win32ui

def pdf_print_device():
    try:
        default_printer = win32print.GetDefaultPrinter()
        printdefaults = {"DesiredAccess": win32print.PRINTER_ALL_ACCESS}
        handle = win32print.OpenPrinter(default_printer, printdefaults)

        try:
            properties = win32print.GetPrinter(handle, 2)
            devmode = properties['pDevMode']
            devmode.PaperLength = 1000
            devmode.PaperWidth = 1000
            devmode.Orientation = win32con.DMORIENT_LANDSCAPE
            properties['pDevMode'] = devmode
            win32print.SetPrinter(handle, 2, properties, 0)
            win32print.SetDefaultPrinter(default_printer)
        except Exception as e:
            print(e)

        text = "test"

        hdc = win32ui.CreateDC()
        hdc.CreatePrinterDC(default_printer)
        hdc.StartDoc("test")

        title = [150, 400, text, {'name': 'Times New Roman', 'height': 135}]
        font = win32ui.CreateFont(title[3])
        hdc.SelectObject(font)
        hdc.TextOut(title[0], title[1], str(title[2]))

        hdc.EndPage()
        hdc.EndDoc()
        win32print.ClosePrinter(handle)
    except Exception as e:
        print(e)


if __name__ == '__main__':
    pdf_print_device()

i hope can change the printer page size

0

There are 0 best solutions below