使用win32和Python直接打印文本文件时隐藏页眉和页脚
我在用这段代码直接打印到文本文件时遇到了问题
win32api.ShellExecute (0, "print", "datafile.txt", None, ".", 0)
每次打印时,它总是会显示“datafile.txt”的标题和“Page1”的页脚。我想在使用连续纸打印时隐藏或去掉这些内容。我不想安装其他第三方软件。请帮帮我。谢谢。
2 个回答
0
使用这个方法,程序员可以获得更多的控制权,而且它不会在没有明确指示的情况下自动添加页眉和页脚。
4
我相信你只需简单搜索一下,就能找到一个比这个临时解决方案更好的模块来处理这个问题(比如使用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)