python – Changing the font when printing to a printer

Question:

You need to print a text file from python. I am using the following code

import tempfile
import win32api
filename = tempfile.mktemp('.txt')
open(filename, 'w').write('Test')
win32api.ShellExecute(0, 'print', filename, None, '.', 0)

(example taken from here link ).

Everything prints, but too large. Is there any way you can change the font?

Answer:

The print system command prints a text file by launching the default text file application (Notepad). This command does not provide the ability to change the font (therefore, the win32api module cannot do this win32api ).

However, before printing, you can change the value of the key responsible for the size of the font in the Windows registry . After printing, replace the value with the original one:

import tempfile
import win32api
import winreg
import time

def do_print():
    """ Исходный код вывода файла на принтер """
    filename = tempfile.mktemp('.txt')
    open(filename, 'w').write('Test')
    win32api.ShellExecute(0, 'print', filename, None, '.', 0)

with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Notepad", 
                    access=winreg.KEY_ALL_ACCESS) as key:
    # Сохранить исходное значение величины шрифта
    value, typ = winreg.QueryValueEx(key, "iPointSize")
    # Изменить размер шрифта - значение величины шрифта нужно умножить на 10
    winreg.SetValueEx(key, "iPointSize", 0, typ, 6*10)

    do_print()
    # Небольшой таймаут для запуска Блокнота
    time.sleep(3)       

    # Вернуть исходное значение
    winreg.SetValueEx(key, "iPointSize", 0, typ, value)

Tested in Python 3.6, Windows 7 64-bit, PDF printer.

Scroll to Top
AllEscort