Reader Daniel Boira recently asked me if I’d experimented with printing large characters on the SparkFun thermal printer (see Hacking a Thermal Till Printer…) that I’d rigged up to my Raspberry Pi’s GPIO. I hadn’t done so, so I thought I’d give it a try.
Lauri Kainulainen’s excellent Python module,
printer.py, provides an easy-to-use interface to most of the printer’s features but not all of them. Double-height and double-width printing are not included. Fortunately, a look at the printer’s command sheet (PDF) reveals there are control codes that can be sent to the printer to enable large characters to be printed.
To that end, I modified my local copy of
printer.py, adding in the following lines within the main body of the
class ThermalPrinter(object): code:
def double_width(self, flag): self.printer.write(self._ESC) if flag == True: self.printer.write(chr(14)) self.DWIDTH = True else: self.printer.write(chr(20)) self.DWIDTH = False def double_height(self, flag): self.printer.write(self._ESC) self.printer.write(chr(33)) if flag == True: if self.DWIDTH == True: self.printer.write(chr(48)) else: self.printer.write(chr(16)) if flag == False: if self.DWIDTH == True: self.printer.write(chr(32)) else: self.printer.write(chr(0))
Usage is simple: just call the double_height function directly through the printer object you’ve established in your own program code. Your program might be something like this:
import printer, textwrap, sys p = printer.ThermalPrinter(serialport="/dev/ttyAMA0") base_text = "This is some text to print" # Turn on double height, width printing p.double_width(True) p.double_height(True) p.print_text(base_text) p.linefeed() # Turn off double height, width printing p.double_width(False) p.double_height(False)
Sending the value
False into either of the two functions flips their respective printing modes on and off, respectively.
Finally, I added a variable,
DWIDTH, to the class defined in
printer.py to track whether double-width printing is enabled or not. The printer provides commands for enabling and disabling double-width printing, but to enable or disable double-height printing, you need to send to the printer a control value that you have to calculate. This value can also enable and disable double-width printing, so the function needs to ‘know’ what the current status of double-width printing is if it’s not to turn it off when you want it on.
To be honest, the same value also alters whether the printer outputs underlined or bold characters. As it stands, if you set the text to bold using
printer.py and then use my additional code to enable double-size printing, you won’t get bold print.
But you’re smart folk – see if you can tweak my code to ‘remember’ the status of bold and underlined printing, and ensure that enabling or disabling double-size printing doesn’t change them.