簡體   English   中英

使用win32和python直接打印時,隱藏文本文件的頁眉和頁腳

[英]hide header and footer on text files when direct print using win32 and python

使用此代碼直接打印到文本文件時,我被困在這里

win32api.ShellExecute (0, "print", "datafile.txt", None, ".", 0)

它總是打印標題“datafile.txt”和頁腳“Page1”。 我想在連續紙張上打印時隱藏或刪除它。 我不想安裝另一個第三方軟件。 請幫我。 謝謝。

我確信你只是一個簡單的搜索,找不到比這個黑客更好地處理這個問題的模塊(例如使用Reportlab和ShellExecute PDF)。 此外,在Windows上打印文本文件的默認應用程序是記事本。 如果要永久配置頁眉/頁腳設置,只需在文件 - >頁面設置中進行更改。

如果您希望在程序中更改記事本的設置,可以使用winreg模塊(Python 2中的_winreg )。 但是,由於ShellExecute不等待作業排隊,因此存在計時問題。 在恢復舊設置之前,您可以暫時休眠或等待用戶input繼續。 這是一個演示過程的快速函數:

try:
    import winreg
except:
    import _winreg as winreg
import win32api

def notepad_print(textfile, newset=None):
    if newset is not None: 
        oldset = {}
        hkcu = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)
        notepad = winreg.OpenKey(hkcu, r'Software\Microsoft\Notepad', 0, 
                                 winreg.KEY_ALL_ACCESS)
        for key, item in newset.items():
            oldset[key] = winreg.QueryValueEx(notepad, key)
            winreg.SetValueEx(notepad, key, None, item[1], item[0])

    #force printing with notepad, instead of using the 'print' verb
    win32api.ShellExecute(0, 'open', 'notepad.exe', '/p ' + textfile, '.', 0)

    input('once the job is queued, hit <enter> to continue')

    if newset is not None:
        for key, item in oldset.items():
            winreg.SetValueEx(notepad, key, None, item[1], item[0])

您可以使用以下調用臨時刪除頁眉/頁腳設置:

notepad_print('datafile.txt', {'szHeader' : ('', 1), 'szTrailer': ('', 1)})

您可以根據需要更改任意數量的注冊表設置:

newset = {
  #name : (value, type)
  'lfFaceName': ('Courier New', 1), 
  'lfWeight': (700, 4),            #400=normal, 700=bold
  'lfUnderline': (0, 4), 
  'lfItalic': (1, 4),              #0=disabled, 1=enabled
  'lfStrikeOut': (0, 4), 
  'iPointSize': (160, 4),          #160 = 16pt
  'iMarginBottom': (1000, 4),      #1 inch
  'iMarginTop': (1000, 4), 
  'iMarginLeft': (750, 4), 
  'iMarginRight': (750, 4), 
  'szHeader': ('&f', 1),            #header '&f'=filename
  'szTrailer': ('Page &p', 1),      #footer '&p'=page number
}

notepad_print('datafile.txt', newset)

使用此方法似乎可以為程序員提供更多控制,當然也不會在沒有顯式語句的情況下插入標題和頁腳。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM