保存/恢复打印机 DevModes - wxPython / win32print

发布于 2024-12-04 18:02:07 字数 1105 浏览 9 评论 0原文

到目前为止,我已经找到了两种不同的方法来从 wxPython 用户界面访问我认为是等效版本的打印机 DevMode:

window = wx.GetTopLevelWindows()[0].GetHandle()
name = self.itemMap['device'].GetValue() # returns a valid printer name.
handle = win32print.OpenPrinter(name)
dmin = None
dmout = pywintypes.DEVMODEType()
mode = DM_IN_BUFFER | DM_OUT_BUFFER | DM_IN_PROMPT

res = win32print.DocumentProperties(window, handle, name, dmout, dmin, mode)

if res == 1:
  print dmout.DriverData

并且

dlg = wx.PrintDialog(self, dgData)

res = dlg.ShowModal()

if res == wx.ID_OK:
  print dlg.GetPrintDialogData().PrintData.GetPrivData()

这些二进制结构似乎包含控制设备输出行为的必要信息。这很好,只是它不能直接用于使用存储的 devmode 数据重新加载 PrintSetup 对话框。在第一种情况下,PyDEVMODE 对象包含数十个需要手动设置的单独属性(PyDEVMODE 参考)。在第二种情况下,有一些 Getter / Setter 方法控制某些属性,但不是所有属性(wxPrintData 参考)。有谁知道从实际的 DevMode (二进制数据)创建 Python Devmode 对象的方法(我将采用任一方法,差异很小)?我想避免必须手动存储/重置每个单独的属性,以便对话框每次都以正确的状态重新打开。

So far I've found two different ways to access what I believe are equivalent versions of the Printer DevMode from a wxPython User Interface:

window = wx.GetTopLevelWindows()[0].GetHandle()
name = self.itemMap['device'].GetValue() # returns a valid printer name.
handle = win32print.OpenPrinter(name)
dmin = None
dmout = pywintypes.DEVMODEType()
mode = DM_IN_BUFFER | DM_OUT_BUFFER | DM_IN_PROMPT

res = win32print.DocumentProperties(window, handle, name, dmout, dmin, mode)

if res == 1:
  print dmout.DriverData

and also

dlg = wx.PrintDialog(self, dgData)

res = dlg.ShowModal()

if res == wx.ID_OK:
  print dlg.GetPrintDialogData().PrintData.GetPrivData()

These to binary structures appear to contain the necessary information to control the device output behavior. This is fine and well, except that it can't be directly used to reload the PrintSetup dialogs with this stored devmode data. In the first case the PyDEVMODE object contains dozens of individual properties that need to be manually set (PyDEVMODE Reference). In the second case there are a handful of Getter / Setter methods that control some of the properties, but not all of them (wxPrintData Reference). Is anyone aware of a way to create a Python Devmode Object (I'll take either approach, the differences are trivial) from the actual DevMode (the binary data)? I'd like to avoid having to manually store / reset each individual attribute in order for the dialogs to re-open in the correct state every time.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不气馁 2024-12-11 18:02:07

您还可以在 win32print.GetPrinter() 中编辑 pDevMode 对象,方法是通过新的命名对象进行操作。

    import win32print, os

    name = win32print.GetDefaultPrinter()
    printdefaults = {"DesiredAccess": win32print.PRINTER_ACCESS_USE}
    handle = win32print.OpenPrinter(name, printdefaults)
    level = 2
    attributes = win32print.GetPrinter(handle, level)   
    # http://timgolden.me.uk/pywin32-docs/PyDEVMODE.html
    # Note: All pDevMode settings are int() variables

    attributes['pDevMode'].Copies = 2    # Num of copies

    #attributes['pDevMode'].Color = 1    # Color
    attributes['pDevMode'].Color = 2    # Monochrome

    attributes['pDevMode'].Collate = 1    # Collate TRUE
    #attributes['pDevMode'].Collate = 2    # Collate FALSE

我在类似的问题中扩展了 Yuri Gendelman 提供的“属性”命名结构: 通过 Python 以双面模式打印 PDF 文件

这是我在代码中如何使用它的示例。

    import win32print, os

    def autoprint(user):                     
        name = win32print.GetDefaultPrinter()
        printdefaults = {"DesiredAccess": win32print.PRINTER_ACCESS_USE}
        handle = win32print.OpenPrinter(name, printdefaults)
        level = 2
        attributes = win32print.GetPrinter(handle, level)   # http://timgolden.me.uk/pywin32-docs/PyDEVMODE.html
                                       # All are int() variables
        attributes['pDevMode'].Duplex = 1    # no flip
        #attributes['pDevMode'].Duplex = 2    # flip up
        #attributes['pDevMode'].Duplex = 3    # flip over

        attributes['pDevMode'].Copies = 2    # Num of copies

        #attributes['pDevMode'].Color = 1    # Color
        attributes['pDevMode'].Color = 2    # Monochrome

        attributes['pDevMode'].Collate = 1    # Collate TRUE
        #attributes['pDevMode'].Collate = 2    # Collate FALSE

        try:
            win32print.SetPrinter(handle, level, attributes, 0)
        except:
            print("win32print.SetPrinter: settings could not be changed")

        try:
            newfile_name = max([downloadPath + "\\" + user["FULL_NAME"] + "PDFToBePrinted.pdf"])
            Print2Copies = win32api.ShellExecute(0, 'print', newfile_name, None, '.', 0)
            time.sleep(1)

            Print2Copies 
            print("Printing now...")
            win32print.ClosePrinter(handle)

            final_filename = max([downloadPath + "\\" + user["FULL_NAME"] + "Printed.pdf"])
            os.rename(newfile_name, final_filename)

        except Exception as e:
            print(str(e))
            print("--Failed to print--")
            time.sleep(5)

以下是检查默认设置的代码:

win32print.GetPrinter(handle, level)['pDevMode'].Copies
win32print.GetPrinter(handle, level)['pDevMode'].Duplex

In[115]: print(win32print.GetPrinter(handle, level)['pDevMode'].Copies)
Out[115]: 1

In[116]:win32print.GetPrinter(handle, level)['pDevMode'].Duplex
Out[116]: 1

In[117]:win32print.GetPrinter(handle, level)['pDevMode'].Color
Out[117]: 1

以下是您可以使用 pDevMode 更改的其他打印机设置:http://timgolden.me.uk/pywin32-docs/PyDEVMODE.html

You can also edit the pDevMode object within win32print.GetPrinter() by manipulating it through a new named object.

    import win32print, os

    name = win32print.GetDefaultPrinter()
    printdefaults = {"DesiredAccess": win32print.PRINTER_ACCESS_USE}
    handle = win32print.OpenPrinter(name, printdefaults)
    level = 2
    attributes = win32print.GetPrinter(handle, level)   
    # http://timgolden.me.uk/pywin32-docs/PyDEVMODE.html
    # Note: All pDevMode settings are int() variables

    attributes['pDevMode'].Copies = 2    # Num of copies

    #attributes['pDevMode'].Color = 1    # Color
    attributes['pDevMode'].Color = 2    # Monochrome

    attributes['pDevMode'].Collate = 1    # Collate TRUE
    #attributes['pDevMode'].Collate = 2    # Collate FALSE

I expanded upon the "attributes" naming structure provided by Yuri Gendelman in a similar question: Print PDF file in duplex mode via Python

Here is a sample of how I used it in my code.

    import win32print, os

    def autoprint(user):                     
        name = win32print.GetDefaultPrinter()
        printdefaults = {"DesiredAccess": win32print.PRINTER_ACCESS_USE}
        handle = win32print.OpenPrinter(name, printdefaults)
        level = 2
        attributes = win32print.GetPrinter(handle, level)   # http://timgolden.me.uk/pywin32-docs/PyDEVMODE.html
                                       # All are int() variables
        attributes['pDevMode'].Duplex = 1    # no flip
        #attributes['pDevMode'].Duplex = 2    # flip up
        #attributes['pDevMode'].Duplex = 3    # flip over

        attributes['pDevMode'].Copies = 2    # Num of copies

        #attributes['pDevMode'].Color = 1    # Color
        attributes['pDevMode'].Color = 2    # Monochrome

        attributes['pDevMode'].Collate = 1    # Collate TRUE
        #attributes['pDevMode'].Collate = 2    # Collate FALSE

        try:
            win32print.SetPrinter(handle, level, attributes, 0)
        except:
            print("win32print.SetPrinter: settings could not be changed")

        try:
            newfile_name = max([downloadPath + "\\" + user["FULL_NAME"] + "PDFToBePrinted.pdf"])
            Print2Copies = win32api.ShellExecute(0, 'print', newfile_name, None, '.', 0)
            time.sleep(1)

            Print2Copies 
            print("Printing now...")
            win32print.ClosePrinter(handle)

            final_filename = max([downloadPath + "\\" + user["FULL_NAME"] + "Printed.pdf"])
            os.rename(newfile_name, final_filename)

        except Exception as e:
            print(str(e))
            print("--Failed to print--")
            time.sleep(5)

Here is the code to check default settings:

win32print.GetPrinter(handle, level)['pDevMode'].Copies
win32print.GetPrinter(handle, level)['pDevMode'].Duplex

In[115]: print(win32print.GetPrinter(handle, level)['pDevMode'].Copies)
Out[115]: 1

In[116]:win32print.GetPrinter(handle, level)['pDevMode'].Duplex
Out[116]: 1

In[117]:win32print.GetPrinter(handle, level)['pDevMode'].Color
Out[117]: 1

Here are the other printer settings you can change with pDevMode: http://timgolden.me.uk/pywin32-docs/PyDEVMODE.html

以歌曲疗慰 2024-12-11 18:02:07

看来目前还没有优雅的方法可以直接在 Python 中实现这一点。我能想到的最接近的是一个用 c++ 编写的 dll,我可以调用它。我最终得到了完整的二进制 DevMode 结构,并且可以从中重新加载。该 c++ dll 的代码如下所示:

#include "stdafx.h"
#include <iobind/base64_policy.hpp>

#include <string>
#ifdef _UNICODE
    typedef std::wstring string_t;
#else
    typedef std::string string_t;
#endif
typedef std::string cstring;


extern "C" BOOL WINAPI DllMain( HMODULE hModule, DWORD dwReason, LPVOID lpReserved ) {
    switch ( dwReason ){
        case DLL_PROCESS_ATTACH:
            DisableThreadLibraryCalls( hModule );
            break;
        case DLL_PROCESS_DETACH:
            break;
    }

    return TRUE;
}


extern "C" DOEXPORT int CleanupA( char *output ) {
    if ( output ) {
        free( output );
        output = NULL;
    }
    return 0;
}


extern "C" DOEXPORT int CleanupW( wchar_t *output ) {
    if ( output ) {
        free( output );
        output = NULL;
    }
    return 0;
}


extern "C" DOEXPORT int printer_setup( 
        void *handle, const TCHAR *printer_in, const char *input,
        int local_only, TCHAR **printer, char **output ) 
{
    HWND hwnd = (HWND)handle;   
    HRESULT hResult = 0;

    LPPRINTDLG pPD = NULL;
    LPPRINTPAGERANGE pPageRanges = NULL;

    // Allocate structure.
    pPD = (LPPRINTDLG)GlobalAlloc(GPTR, sizeof(PRINTDLG));
    if (!pPD) return E_OUTOFMEMORY;

    //  Initialize structure.
    pPD->lStructSize = sizeof(PRINTDLG);
    pPD->hwndOwner = hwnd;

    pPD->hDevMode = NULL;
    if ( input ){
        std::string dec = iobind::encode( input, iobind::from_base64_p );
        if ( !dec.empty() ) {
            HGLOBAL devmode = pPD->hDevMode = ::GlobalAlloc(GPTR, dec.size());
            if ( devmode ){         
                LPDEVMODE src = (LPDEVMODE)&dec[0];
                memcpy( devmode, src, dec.size() );
            }
        }
    }

    pPD->hDevNames = NULL;
    if ( printer_in ){
        HGLOBAL printer = pPD->hDevNames = ::GlobalAlloc(GPTR, sizeof(DEVNAMES)+_tcslen(printer_in)*sizeof(TCHAR)+sizeof(TCHAR));
        if ( printer ){
            LPDEVNAMES dv = (LPDEVNAMES)printer;
            dv->wDefault = 0;
            dv->wDriverOffset = 0;
            dv->wOutputOffset = 0;
            dv->wDeviceOffset = sizeof(DEVNAMES)/sizeof(TCHAR);
            TCHAR *dest = (TCHAR *)(unsigned long)dv + dv->wDeviceOffset;
            _tcscpy( dest, printer_in );
        }
    }

    pPD->hDC = NULL;
    pPD->Flags = PD_PRINTSETUP;

    if ( local_only ) {
        pPD->Flags |= /*PD_ENABLESETUPHOOK |*/ PD_NONETWORKBUTTON;
    }

    pPD->nMinPage = 1;
    pPD->nMaxPage = 1000;
    pPD->nCopies = 1;
    pPD->hInstance = 0;
    pPD->lpPrintTemplateName = NULL;

    //  Invoke the Print property sheet.
    hResult = PrintDlg(pPD);
    if ( hResult != 0 ) {
        if ( pPD->hDevMode ) {
            LPDEVMODE devmode = (LPDEVMODE)::GlobalLock( pPD->hDevMode );
            size_t size = devmode->dmSize + devmode->dmDriverExtra;
            if ( output ) {
                std::string tmp;
                tmp.resize( size );
                memcpy( &tmp[0], devmode, tmp.size() );

                std::string enc = iobind::encode( tmp, iobind::to_base64_p );
                *output = _strdup( enc.c_str() );
            }
            ::GlobalUnlock( pPD->hDevMode );
        }

        if ( pPD->hDevNames ) {
            LPDEVNAMES devnames = (LPDEVNAMES)::GlobalLock( pPD->hDevNames );
            TCHAR *device = (TCHAR *)(unsigned long)devnames + devnames->wDeviceOffset;
            *printer = _tcsdup(device);
            ::GlobalUnlock( pPD->hDevNames );
        }
    }
    else {
        DWORD dlgerr = ::CommDlgExtendedError();
        hResult = dlgerr;
    }

    if (pPD->hDC != NULL) {
        DeleteDC( pPD->hDC );
    }
    if (pPD->hDevMode != NULL) { 
        GlobalFree( pPD->hDevMode );
    }
    if (pPD->hDevNames != NULL) {
        GlobalFree( pPD->hDevNames );
    }
    return hResult;
}

在 Python 中,它的调用方式如下:

client = ctypes.cdll.LoadLibrary(os.path.join(myDir, 'rpmclient.dll'))
client.printer_setup.argtypes = [ctypes.c_void_p,
                                 ctypes.c_wchar_p,
                                 ctypes.c_char_p,
                                 ctypes.c_int32,
                                 ctypes.POINTER(ctypes.c_wchar_p),
                                 ctypes.POINTER(ctypes.c_char_p)]

client.printer_setup.restype = ctypes.c_int32
client.CleanupA.argtypes = [ctypes.c_char_p]
client.CleanupA.restype = ctypes.c_int32
client.CleanupW.argtypes = [ctypes.c_wchar_p]
client.CleanupW.restype = ctypes.c_int32

p_in = ctypes.c_wchar_p(self.itemMap['device'].GetValue())
p_out = ctypes.c_wchar_p()

d_in = ctypes.c_char_p(getattr(self, 'devmode', ''))
d_out = ctypes.c_char_p()

res = client.printer_setup(self.GetHandle(),
                           p_in,
                           d_in,
                           False,
                           p_out,
                           d_out)

if res == 0:
  return

if res > 1:
  # Error display code here.

  return

self.devmode = d_out.value

It appears that at this point there's no elegant way to achieve this directly in Python. The closest I was able to come up with was a dll written in c++ that I'm able to call into. I end up with the full binary DevMode Structure, and can reload from it. The code for that c++ dll looks like this:

#include "stdafx.h"
#include <iobind/base64_policy.hpp>

#include <string>
#ifdef _UNICODE
    typedef std::wstring string_t;
#else
    typedef std::string string_t;
#endif
typedef std::string cstring;


extern "C" BOOL WINAPI DllMain( HMODULE hModule, DWORD dwReason, LPVOID lpReserved ) {
    switch ( dwReason ){
        case DLL_PROCESS_ATTACH:
            DisableThreadLibraryCalls( hModule );
            break;
        case DLL_PROCESS_DETACH:
            break;
    }

    return TRUE;
}


extern "C" DOEXPORT int CleanupA( char *output ) {
    if ( output ) {
        free( output );
        output = NULL;
    }
    return 0;
}


extern "C" DOEXPORT int CleanupW( wchar_t *output ) {
    if ( output ) {
        free( output );
        output = NULL;
    }
    return 0;
}


extern "C" DOEXPORT int printer_setup( 
        void *handle, const TCHAR *printer_in, const char *input,
        int local_only, TCHAR **printer, char **output ) 
{
    HWND hwnd = (HWND)handle;   
    HRESULT hResult = 0;

    LPPRINTDLG pPD = NULL;
    LPPRINTPAGERANGE pPageRanges = NULL;

    // Allocate structure.
    pPD = (LPPRINTDLG)GlobalAlloc(GPTR, sizeof(PRINTDLG));
    if (!pPD) return E_OUTOFMEMORY;

    //  Initialize structure.
    pPD->lStructSize = sizeof(PRINTDLG);
    pPD->hwndOwner = hwnd;

    pPD->hDevMode = NULL;
    if ( input ){
        std::string dec = iobind::encode( input, iobind::from_base64_p );
        if ( !dec.empty() ) {
            HGLOBAL devmode = pPD->hDevMode = ::GlobalAlloc(GPTR, dec.size());
            if ( devmode ){         
                LPDEVMODE src = (LPDEVMODE)&dec[0];
                memcpy( devmode, src, dec.size() );
            }
        }
    }

    pPD->hDevNames = NULL;
    if ( printer_in ){
        HGLOBAL printer = pPD->hDevNames = ::GlobalAlloc(GPTR, sizeof(DEVNAMES)+_tcslen(printer_in)*sizeof(TCHAR)+sizeof(TCHAR));
        if ( printer ){
            LPDEVNAMES dv = (LPDEVNAMES)printer;
            dv->wDefault = 0;
            dv->wDriverOffset = 0;
            dv->wOutputOffset = 0;
            dv->wDeviceOffset = sizeof(DEVNAMES)/sizeof(TCHAR);
            TCHAR *dest = (TCHAR *)(unsigned long)dv + dv->wDeviceOffset;
            _tcscpy( dest, printer_in );
        }
    }

    pPD->hDC = NULL;
    pPD->Flags = PD_PRINTSETUP;

    if ( local_only ) {
        pPD->Flags |= /*PD_ENABLESETUPHOOK |*/ PD_NONETWORKBUTTON;
    }

    pPD->nMinPage = 1;
    pPD->nMaxPage = 1000;
    pPD->nCopies = 1;
    pPD->hInstance = 0;
    pPD->lpPrintTemplateName = NULL;

    //  Invoke the Print property sheet.
    hResult = PrintDlg(pPD);
    if ( hResult != 0 ) {
        if ( pPD->hDevMode ) {
            LPDEVMODE devmode = (LPDEVMODE)::GlobalLock( pPD->hDevMode );
            size_t size = devmode->dmSize + devmode->dmDriverExtra;
            if ( output ) {
                std::string tmp;
                tmp.resize( size );
                memcpy( &tmp[0], devmode, tmp.size() );

                std::string enc = iobind::encode( tmp, iobind::to_base64_p );
                *output = _strdup( enc.c_str() );
            }
            ::GlobalUnlock( pPD->hDevMode );
        }

        if ( pPD->hDevNames ) {
            LPDEVNAMES devnames = (LPDEVNAMES)::GlobalLock( pPD->hDevNames );
            TCHAR *device = (TCHAR *)(unsigned long)devnames + devnames->wDeviceOffset;
            *printer = _tcsdup(device);
            ::GlobalUnlock( pPD->hDevNames );
        }
    }
    else {
        DWORD dlgerr = ::CommDlgExtendedError();
        hResult = dlgerr;
    }

    if (pPD->hDC != NULL) {
        DeleteDC( pPD->hDC );
    }
    if (pPD->hDevMode != NULL) { 
        GlobalFree( pPD->hDevMode );
    }
    if (pPD->hDevNames != NULL) {
        GlobalFree( pPD->hDevNames );
    }
    return hResult;
}

In Python, it's called into like so:

client = ctypes.cdll.LoadLibrary(os.path.join(myDir, 'rpmclient.dll'))
client.printer_setup.argtypes = [ctypes.c_void_p,
                                 ctypes.c_wchar_p,
                                 ctypes.c_char_p,
                                 ctypes.c_int32,
                                 ctypes.POINTER(ctypes.c_wchar_p),
                                 ctypes.POINTER(ctypes.c_char_p)]

client.printer_setup.restype = ctypes.c_int32
client.CleanupA.argtypes = [ctypes.c_char_p]
client.CleanupA.restype = ctypes.c_int32
client.CleanupW.argtypes = [ctypes.c_wchar_p]
client.CleanupW.restype = ctypes.c_int32

p_in = ctypes.c_wchar_p(self.itemMap['device'].GetValue())
p_out = ctypes.c_wchar_p()

d_in = ctypes.c_char_p(getattr(self, 'devmode', ''))
d_out = ctypes.c_char_p()

res = client.printer_setup(self.GetHandle(),
                           p_in,
                           d_in,
                           False,
                           p_out,
                           d_out)

if res == 0:
  return

if res > 1:
  # Error display code here.

  return

self.devmode = d_out.value
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文