pythonprintinggtk

How do I create and print a document (to a printer) using Gtk?


I want to create a document and print it to a printer using my Gtk 3 app. I'm using Python 3. Here is the simplified code:

import gi
import os

gi.require_version("Gtk", "3.0")

from gi.repository import Gtk, Pango

parent = Gtk.Window()

printers = os.popen("lpstat -e").read().strip().split("\n")
print("Available printers: %s" % printers)

printcontext = Gtk.PrintContext()
context = printcontext.create_pango_context()
layout = Pango.Layout.new(context)
layout.set_text("Hello!")
printsettings = Gtk.PrintSettings()
print("Printing to: %s" % printers[0])

printsettings.set_printer(printers[0])
printsettings.set_print_pages(Gtk.PrintPages.ALL)
printoperation = Gtk.PrintOperation().new()
printoperation.set_print_settings(printsettings)
print("Printing result: %s" % 
printoperation.run(Gtk.PrintOperationAction.PRINT, parent))

but when I run it with the printer connected, it cancels the operation:

Available printers: ['Canon-MF210-Series', 'HP_Officejet_5740_series_434FB1_']
Printing to: Canon-MF210-Series
Printing result: <enum GTK_PRINT_OPERATION_RESULT_CANCEL of type Gtk.PrintOperationResult>

Why is it cancelling the PrintOperation with no error messages, and how can I get it to print properly? My system is an Ubuntu 20.04.2, if that helps.


Solution

  • I found another solution! Using the cups module, you can get a list of the available printers, select one, and print a file to it! Here is an example:

    import cups
    import cupshelpers
    
    # Create a new connection and the list of available printers
    connection = cups.Connection()
    printers = cupshelpers.getPrinters(connection)
    
    # Select the first printer in the list...
    for p in printers:
        if p is not None:
            printer = printers[p]
            break
    
    # ...and print to it
    printer.connection.printFile(
        p,
        "printer_test.txt",
        "Test this printer",
        {}
    )
    

    This can print several types of files, like PDF and plaintext. I'll update this answer if I find anything out about the options dictionary in the printer.connection.printFile() function. Unfortunately, this doesn't answer the how to create a file with Gtk question, but there are plenty of questions on how to create and edit PDFs.

    Note: No guarantee that this works on Windows. If you have a Windows, you may want to look at Brody Critchlow's answer.