当使用此代码直接打印到文本文件时,我被困在这里
win32api.ShellExecute (0, "print", "datafile.txt", None, ".", 0)
它总是打印页眉"datafile.txt"和页脚"Page1"。我想隐藏或删除这在连续的形式纸上打印时。我不想再安装第三方软件了。请帮帮我。谢谢。
我相信你只是一个简单的搜索远离找到一个模块,将处理这个问题比这个hack(例如使用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'SoftwareMicrosoftNotepad', 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)
使用这种方法似乎给了程序员更多的控制,当然不会在没有显式语句的情况下插入头和脚。