Chapter 24. Printing

Table of Contents
The QPrinter class
Adding printing to Kalam
Putting ink to paper
Conclusion

Printing: a subject that strikes fear into the heart of even the most stalwart developer—and with good reason. Getting a user's application data neatly on paper demands a lot of skill.

Common problems include different printer capabilities, differences between fonts on screen and on the printer, differing paper sizes, and platform differences in getting the output to the printer.

PyQt brings a measure of relief to some of these problems, though not to all. It provides you with the QPrinter object, which is a type of QPaintDevice that has a built-in common dialog for printer settings. This takes care of most problems associated with font handling and printer capabilities. With Qt 3 you can even send TrueType fonts to the printer. The hard work—the layout of the page for paper—is still your job.

Printing on Unix/X11 requires creating PostScript files and sending them to lpr. On Windows systems you can use the built-in printer drivers. On a Unix system you can always chicken out; if your application data is plain text or source code, you can spool it directly to the printer, or via a pretty-printing program such as a2ps.

For the moment, we will not pursue that option, and instead use QPrinter to add printing capabilities to Kalam.

The QPrinter class

Generally speaking, there will be only one active printer attached to a user's system. This means that we will keep a single reference to a QPrinter object. Therefore, we might as well create the QPrinter in the __init__() method of the KalamApp class.

# kalamapp.py

class KalamApp(QMainWindow):
    """KalamApp is the toplevel application window of the kalam unicode editor
    application.
    """
    def __init__(self, *args):
        apply(QMainWindow.__init__,(self, ) + args)
        ...
        # Create the printer object
        self.printer = QPrinter()
        ...
    

QPrinter is more configurable than most QPaintDevices. You can set the printer, printer driver, paper size, number of copies to be printed, and so on. You can set those configuration options programmatically, but some of them can also be changed by the user. If you call the setup() function on the printer object, a printer setup dialog will popup:

The printer setup dialog