#StackBounty: #python #printing #gtk How do I create and print a document (to a printer) using Gtk?

Bounty: 50

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.


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.