ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

使用Win32和python直接打印时,在文本文件上隐藏页眉和页脚

2019-11-02 10:57:26  阅读:345  来源: 互联网

标签:pywin32 text-files system-printing python


使用此代码直接打印到文本文件时,我被卡在这里

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

它总是打印页眉“ datafile.txt”和页脚“ Page1”.在连续纸上打印时,我想隐藏或删除它.我不想安装其他第三方软件.请帮我.谢谢.

解决方法:

我敢肯定,您只是简单的搜索工作,而不是找到比此hack更好地解决此问题的模块(例如,使用Reportlab和ShellExecute PDF).另外,在Windows上打印文本文件的默认应用程序是记事本.如果您希望永久配置页眉/页脚设置,只需在“文件”->“页面设置”中进行更改即可.

如果要在程序中更改记事本的设置,则可以使用winreg模块(Python 2中为_winreg).但是,由于ShellExecute不等待作业排队,因此存在计时问题.在恢复旧设置之前,您可以睡一会儿或等待用户输入继续.这是演示该过程的快速功能:

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)

标签:pywin32,text-files,system-printing,python
来源: https://codeday.me/bug/20191102/1990785.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有