Skip to content

Gtk.PrintOperation

class — extends GObject.Object, PrintOperationPreview

High-level, portable printing API.

It looks a bit different than other GTK dialogs such as the GtkFileChooser, since some platforms don’t expose enough infrastructure to implement a good print dialog. On such platforms, GtkPrintOperation uses the native print dialog. On platforms which do not provide a native print dialog, GTK uses its own, see PrintUnixDialog.

The typical way to use the high-level printing API is to create a GtkPrintOperation object with PrintOperation.new when the user selects to print. Then you set some properties on it, e.g. the page size, any PrintSettings from previous print operations, the number of pages, the current page, etc.

Then you start the print operation by calling PrintOperation.run. It will then show a dialog, let the user select a printer and options. When the user finished the dialog, various signals will be emitted on the GtkPrintOperation, the main one being PrintOperation.draw-page, which you are supposed to handle and render the page on the provided PrintContext using Cairo.

The high-level printing API

static GtkPrintSettings *settings = NULL;

static void
do_print (void)
{
  GtkPrintOperation *print;
  GtkPrintOperationResult res;

  print = gtk_print_operation_new ();

  if (settings != NULL)
    gtk_print_operation_set_print_settings (print, settings);

  g_signal_connect (print, "begin_print", G_CALLBACK (begin_print), NULL);
  g_signal_connect (print, "draw_page", G_CALLBACK (draw_page), NULL);

  res = gtk_print_operation_run (print, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG,
                                 GTK_WINDOW (main_window), NULL);

  if (res == GTK_PRINT_OPERATION_RESULT_APPLY)
    {
      if (settings != NULL)
        g_object_unref (settings);
      settings = g_object_ref (gtk_print_operation_get_print_settings (print));
    }

  g_object_unref (print);
}

By default GtkPrintOperation uses an external application to do print preview. To implement a custom print preview, an application must connect to the preview signal. The functions PrintOperationPreview.render_page, PrintOperationPreview.end_preview and PrintOperationPreview.is_selected are useful when implementing a print preview.

Constructors

new

@classmethod
def new(cls) -> PrintOperation

Creates a new GtkPrintOperation.

Methods

cancel

def cancel(self) -> None

Cancels a running print operation.

This function may be called from a PrintOperation.begin-print, PrintOperation.paginate or PrintOperation.draw-page signal handler to stop the currently running print operation.

draw_page_finish

def draw_page_finish(self) -> None

Signal that drawing of particular page is complete.

It is called after completion of page drawing (e.g. drawing in another thread). If PrintOperation.set_defer_drawing was called before, then this function has to be called by application. Otherwise it is called by GTK itself.

get_default_page_setup

def get_default_page_setup(self) -> PageSetup

Returns the default page setup.

get_embed_page_setup

def get_embed_page_setup(self) -> bool

Gets whether page setup selection combos are embedded

get_error

def get_error(self) -> None

Call this when the result of a print operation is PrintOperationResult.ERROR.

It can be called either after PrintOperation.run returns, or in the PrintOperation.done signal handler.

The returned GError will contain more details on what went wrong.

get_has_selection

def get_has_selection(self) -> bool

Gets whether there is a selection.

get_n_pages_to_print

def get_n_pages_to_print(self) -> int

Returns the number of pages that will be printed.

Note that this value is set during print preparation phase (PrintStatus.PREPARING), so this function should never be called before the data generation phase (PrintStatus.GENERATING_DATA). You can connect to the PrintOperation.status-changed signal and call PrintOperation.get_n_pages_to_print when print status is PrintStatus.GENERATING_DATA.

This is typically used to track the progress of print operation.

get_print_settings

def get_print_settings(self) -> PrintSettings | None

Returns the current print settings.

Note that the return value is None until either PrintOperation.set_print_settings or PrintOperation.run have been called.

get_status

def get_status(self) -> PrintStatus

Returns the status of the print operation.

Also see PrintOperation.get_status_string.

get_status_string

def get_status_string(self) -> str

Returns a string representation of the status of the print operation.

The string is translated and suitable for displaying the print status e.g. in a GtkStatusbar.

Use PrintOperation.get_status to obtain a status value that is suitable for programmatic use.

get_support_selection

def get_support_selection(self) -> bool

Gets whether the application supports print of selection

is_finished

def is_finished(self) -> bool

A convenience function to find out if the print operation is finished.

a print operation is finished if its status is either PrintStatus.FINISHED or PrintStatus.FINISHED_ABORTED.

Note: when you enable print status tracking the print operation can be in a non-finished state even after done has been called, as the operation status then tracks the print job status on the printer.

run

def run(self, action: PrintOperationAction | int, parent: Window | None = ...) -> PrintOperationResult

Runs the print operation.

Normally that this function does not return until the rendering of all pages is complete. You can connect to the PrintOperation.status-changed signal on op to obtain some information about the progress of the print operation.

Furthermore, it may use a recursive mainloop to show the print dialog.

If you set the [Gtk.PrintOperation:allow-async] property, the operation will run asynchronously if this is supported on the platform. The PrintOperation.done signal will be emitted with the result of the operation when the it is done (i.e. when the dialog is canceled, or when the print succeeds or fails).

if (settings != NULL)
  gtk_print_operation_set_print_settings (print, settings);

if (page_setup != NULL)
  gtk_print_operation_set_default_page_setup (print, page_setup);

g_signal_connect (print, "begin-print",
                  G_CALLBACK (begin_print), &data);
g_signal_connect (print, "draw-page",
                  G_CALLBACK (draw_page), &data);

res = gtk_print_operation_run (print,
                               GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG,
                               parent,
                               &error);

if (res == GTK_PRINT_OPERATION_RESULT_ERROR)
 {
   error_dialog = gtk_message_dialog_new (GTK_WINDOW (parent),
                                 GTK_DIALOG_DESTROY_WITH_PARENT,
                         GTK_MESSAGE_ERROR,
                         GTK_BUTTONS_CLOSE,
                         "Error printing file:\n%s",
                         error->message);
   g_signal_connect (error_dialog, "response",
                     G_CALLBACK (gtk_window_destroy), NULL);
   gtk_window_present (GTK_WINDOW (error_dialog));
   g_error_free (error);
 }
else if (res == GTK_PRINT_OPERATION_RESULT_APPLY)
 {
   if (settings != NULL)
g_object_unref (settings);
   settings = g_object_ref (gtk_print_operation_get_print_settings (print));
 }

Note that PrintOperation.run can only be called once on a given GtkPrintOperation.

Parameters:

  • action — the action to start
  • parent — Transient parent of the dialog

set_allow_async

def set_allow_async(self, allow_async: bool) -> None

Sets whether PrintOperation.run may return before the print operation is completed.

Note that some platforms may not allow asynchronous operation.

Parameters:

  • allow_asyncTrue to allow asynchronous operation

set_current_page

def set_current_page(self, current_page: int) -> None

Sets the current page.

If this is called before PrintOperation.run, the user will be able to select to print only the current page.

Note that this only makes sense for pre-paginated documents.

Parameters:

  • current_page — the current page, 0-based

set_custom_tab_label

def set_custom_tab_label(self, label: str | None = ...) -> None

Sets the label for the tab holding custom widgets.

Parameters:

  • label — the label to use, or None to use the default label

set_default_page_setup

def set_default_page_setup(self, default_page_setup: PageSetup | None = ...) -> None

Makes default_page_setup the default page setup for op.

This page setup will be used by PrintOperation.run, but it can be overridden on a per-page basis by connecting to the PrintOperation.request-page-setup signal.

Parameters:

  • default_page_setup — a GtkPageSetup

set_defer_drawing

def set_defer_drawing(self) -> None

Sets up the GtkPrintOperation to wait for calling of [methodGtk.PrintOperation.draw_page_finish from application.

This can be used for drawing page in another thread.

This function must be called in the callback of the PrintOperation.draw-page signal.

set_embed_page_setup

def set_embed_page_setup(self, embed: bool) -> None

Embed page size combo box and orientation combo box into page setup page.

Selected page setup is stored as default page setup in GtkPrintOperation.

Parameters:

  • embedTrue to embed page setup selection in the GtkPrintUnixDialog

set_export_filename

def set_export_filename(self, filename: str | bytes | os.PathLike[str] | os.PathLike[bytes]) -> None

Sets up the GtkPrintOperation to generate a file instead of showing the print dialog.

The intended use of this function is for implementing “Export to PDF” actions. Currently, PDF is the only supported format.

“Print to PDF” support is independent of this and is done by letting the user pick the “Print to PDF” item from the list of printers in the print dialog.

Parameters:

  • filename — the filename for the exported file

set_has_selection

def set_has_selection(self, has_selection: bool) -> None

Sets whether there is a selection to print.

Application has to set number of pages to which the selection will draw by PrintOperation.set_n_pages in a handler for the PrintOperation.begin-print signal.

Parameters:

  • has_selectionTrue indicates that a selection exists

set_job_name

def set_job_name(self, job_name: str) -> None

Sets the name of the print job.

The name is used to identify the job (e.g. in monitoring applications like eggcups).

If you don’t set a job name, GTK picks a default one by numbering successive print jobs.

Parameters:

  • job_name — a string that identifies the print job

set_n_pages

def set_n_pages(self, n_pages: int) -> None

Sets the number of pages in the document.

This must be set to a positive number before the rendering starts. It may be set in a PrintOperation.begin-print signal handler.

Note that the page numbers passed to the PrintOperation.request-page-setup and PrintOperation.draw-page signals are 0-based, i.e. if the user chooses to print all pages, the last ::draw-page signal will be for page n_pages - 1.

Parameters:

  • n_pages — the number of pages

set_print_settings

def set_print_settings(self, print_settings: PrintSettings | None = ...) -> None

Sets the print settings for op.

This is typically used to re-establish print settings from a previous print operation, see PrintOperation.run.

Parameters:

  • print_settingsGtkPrintSettings

set_show_progress

def set_show_progress(self, show_progress: bool) -> None

If show_progress is True, the print operation will show a progress dialog during the print operation.

Parameters:

  • show_progressTrue to show a progress dialog

set_support_selection

def set_support_selection(self, support_selection: bool) -> None

Sets whether selection is supported by GtkPrintOperation.

Parameters:

  • support_selectionTrue to support selection

set_track_print_status

def set_track_print_status(self, track_status: bool) -> None

If track_status is True, the print operation will try to continue report on the status of the print job in the printer queues and printer.

This can allow your application to show things like “out of paper” issues, and when the print job actually reaches the printer.

This function is often implemented using some form of polling, so it should not be enabled unless needed.

Parameters:

  • track_statusTrue to track status after printing

set_unit

def set_unit(self, unit: Unit | int) -> None

Sets up the transformation for the cairo context obtained from GtkPrintContext in such a way that distances are measured in units of unit.

Parameters:

  • unit — the unit to use

set_use_full_page

def set_use_full_page(self, full_page: bool) -> None

If full_page is True, the transformation for the cairo context obtained from GtkPrintContext puts the origin at the top left corner of the page.

This may not be the top left corner of the sheet, depending on page orientation and the number of pages per sheet). Otherwise, the origin is at the top left corner of the imageable area (i.e. inside the margins).

Parameters:

  • full_pageTrue to set up the GtkPrintContext for the full page

Virtual methods

do_begin_print

def do_begin_print(self, context: PrintContext) -> None

Signal emitted after the user has finished changing print settings in the dialog, before the actual rendering starts.

do_custom_widget_apply

def do_custom_widget_apply(self, widget: Widget) -> None

Signal emitted right before “begin-print” if you added a custom widget in the “create-custom-widget” handler.

do_done

def do_done(self, result: PrintOperationResult | int) -> None

Signal emitted when the print operation run has finished doing everything required for printing.

do_draw_page

def do_draw_page(self, context: PrintContext, page_nr: int) -> None

Signal emitted for every page that is printed.

do_end_print

def do_end_print(self, context: PrintContext) -> None

Signal emitted after all pages have been rendered.

do_paginate

def do_paginate(self, context: PrintContext) -> bool

Signal emitted after the “begin-print” signal, but before the actual rendering starts.

do_preview

def do_preview(self, preview: PrintOperationPreview, context: PrintContext, parent: Window) -> bool

Signal emitted when a preview is requested from the native dialog.

do_request_page_setup

def do_request_page_setup(self, context: PrintContext, page_nr: int, setup: PageSetup) -> None

Emitted once for every page that is printed, to give the application a chance to modify the page setup.

do_status_changed

def do_status_changed(self) -> None

Emitted at between the various phases of the print operation.

do_update_custom_widget

def do_update_custom_widget(self, widget: Widget, setup: PageSetup, settings: PrintSettings) -> None

Emitted after change of selected printer.

Properties

allow_async

allow_async: bool  # read/write

Determines whether the print operation may run asynchronously or not.

Some systems don't support asynchronous printing, but those that do will return PrintOperationResult.IN_PROGRESS as the status, and emit the PrintOperation.done signal when the operation is actually done.

The Windows port does not support asynchronous operation at all (this is unlikely to change). On other platforms, all actions except for PrintOperationAction.EXPORT support asynchronous operation.

current_page

current_page: int  # read/write

The current page in the document.

If this is set before PrintOperation.run, the user will be able to select to print only the current page.

Note that this only makes sense for pre-paginated documents.

custom_tab_label

custom_tab_label: str  # read/write

Used as the label of the tab containing custom widgets.

Note that this property may be ignored on some platforms.

If this is None, GTK uses a default label.

default_page_setup

default_page_setup: PageSetup  # read/write

The GtkPageSetup used by default.

This page setup will be used by PrintOperation.run, but it can be overridden on a per-page basis by connecting to the PrintOperation.request-page-setup signal.

embed_page_setup

embed_page_setup: bool  # read/write

If True, page size combo box and orientation combo box are embedded into page setup page.

export_filename

export_filename: str  # read/write

The name of a file to generate instead of showing the print dialog.

Currently, PDF is the only supported format.

The intended use of this property is for implementing “Export to PDF” actions.

“Print to PDF” support is independent of this and is done by letting the user pick the “Print to PDF” item from the list of printers in the print dialog.

has_selection

has_selection: bool  # read/write

Determines whether there is a selection in your application.

This can allow your application to print the selection. This is typically used to make a "Selection" button sensitive.

job_name

job_name: str  # read/write

A string used to identify the job (e.g. in monitoring applications like eggcups).

If you don't set a job name, GTK picks a default one by numbering successive print jobs.

n_pages

n_pages: int  # read/write

The number of pages in the document.

This must be set to a positive number before the rendering starts. It may be set in a PrintOperation.begin-print signal handler.

Note that the page numbers passed to the PrintOperation.request-page-setup and PrintOperation.draw-page signals are 0-based, i.e. if the user chooses to print all pages, the last ::draw-page signal will be for page n_pages - 1.

n_pages_to_print

n_pages_to_print: int  # read-only

The number of pages that will be printed.

Note that this value is set during print preparation phase (PrintStatus.PREPARING), so this value should never be get before the data generation phase (PrintStatus.GENERATING_DATA). You can connect to the PrintOperation.status-changed signal and call PrintOperation.get_n_pages_to_print when print status is PrintStatus.GENERATING_DATA.

This is typically used to track the progress of print operation.

print_settings

print_settings: PrintSettings  # read/write

The GtkPrintSettings used for initializing the dialog.

Setting this property is typically used to re-establish print settings from a previous print operation, see PrintOperation.run.

show_progress

show_progress: bool  # read/write

Determines whether to show a progress dialog during the print operation.

status

status: PrintStatus | int  # read-only

The status of the print operation.

status_string

status_string: str  # read-only

A string representation of the status of the print operation.

The string is translated and suitable for displaying the print status e.g. in a GtkStatusbar.

See the PrintOperation.status property for a status value that is suitable for programmatic use.

support_selection

support_selection: bool  # read/write

If True, the print operation will support print of selection.

This allows the print dialog to show a "Selection" button.

track_print_status

track_print_status: bool  # read/write

If True, the print operation will try to continue report on the status of the print job in the printer queues and printer.

This can allow your application to show things like “out of paper” issues, and when the print job actually reaches the printer. However, this is often implemented using polling, and should not be enabled unless needed.

unit

unit: Unit | int  # read/write

The transformation for the cairo context obtained from GtkPrintContext is set up in such a way that distances are measured in units of unit.

use_full_page

use_full_page: bool  # read/write

If True, the transformation for the cairo context obtained from GtkPrintContext puts the origin at the top left corner of the page.

This may not be the top left corner of the sheet, depending on page orientation and the number of pages per sheet. Otherwise, the origin is at the top left corner of the imageable area (i.e. inside the margins).

Signals

begin-print

def on_begin_print(self, context: PrintContext) -> None: ...

Emitted after the user has finished changing print settings in the dialog, before the actual rendering starts.

A typical use for ::begin-print is to use the parameters from the PrintContext and paginate the document accordingly, and then set the number of pages with PrintOperation.set_n_pages.

create-custom-widget

def on_create_custom_widget(self) -> GObject.Object | None: ...

Emitted when displaying the print dialog.

If you return a widget in a handler for this signal it will be added to a custom tab in the print dialog. You typically return a container widget with multiple widgets in it.

The print dialog owns the returned widget, and its lifetime is not controlled by the application. However, the widget is guaranteed to stay around until the PrintOperation.custom-widget-apply signal is emitted on the operation. Then you can read out any information you need from the widgets.

custom-widget-apply

def on_custom_widget_apply(self, widget: Widget) -> None: ...

Emitted right before ::begin-print if you added a custom widget in the ::create-custom-widget handler.

When you get this signal you should read the information from the custom widgets, as the widgets are not guaranteed to be around at a later time.

done

def on_done(self, result: PrintOperationResult) -> None: ...

Emitted when the print operation run has finished doing everything required for printing.

result gives you information about what happened during the run. If result is PrintOperationResult.ERROR then you can call PrintOperation.get_error for more information.

If you enabled print status tracking then PrintOperation.is_finished may still return False after the ::done signal was emitted.

draw-page

def on_draw_page(self, context: PrintContext, page_nr: int) -> None: ...

Emitted for every page that is printed.

The signal handler must render the page_nr's page onto the cairo context obtained from context using PrintContext.get_cairo_context.

static void
draw_page (GtkPrintOperation *operation,
           GtkPrintContext   *context,
           int                page_nr,
           gpointer           user_data)
{
  cairo_t *cr;
  PangoLayout *layout;
  double width, text_height;
  int layout_height;
  PangoFontDescription *desc;

  cr = gtk_print_context_get_cairo_context (context);
  width = gtk_print_context_get_width (context);

  cairo_rectangle (cr, 0, 0, width, HEADER_HEIGHT);

  cairo_set_source_rgb (cr, 0.8, 0.8, 0.8);
  cairo_fill (cr);

  layout = gtk_print_context_create_pango_layout (context);

  desc = pango_font_description_from_string ("sans 14");
  pango_layout_set_font_description (layout, desc);
  pango_font_description_free (desc);

  pango_layout_set_text (layout, "some text", -1);
  pango_layout_set_width (layout, width * PANGO_SCALE);
  pango_layout_set_alignment (layout, PANGO_ALIGN_CENTER);

  pango_layout_get_size (layout, NULL, &layout_height);
  text_height = (double)layout_height / PANGO_SCALE;

  cairo_move_to (cr, width / 2,  (HEADER_HEIGHT - text_height) / 2);
  pango_cairo_show_layout (cr, layout);

  g_object_unref (layout);
}

Use PrintOperation.set_use_full_page and PrintOperation.set_unit before starting the print operation to set up the transformation of the cairo context according to your needs.

end-print

def on_end_print(self, context: PrintContext) -> None: ...

Emitted after all pages have been rendered.

A handler for this signal can clean up any resources that have been allocated in the PrintOperation.begin-print handler.

paginate

def on_paginate(self, context: PrintContext) -> bool: ...

Emitted after the ::begin-print signal, but before the actual rendering starts.

It keeps getting emitted until a connected signal handler returns True.

The ::paginate signal is intended to be used for paginating a document in small chunks, to avoid blocking the user interface for a long time. The signal handler should update the number of pages using PrintOperation.set_n_pages, and return True if the document has been completely paginated.

If you don't need to do pagination in chunks, you can simply do it all in the ::begin-print handler, and set the number of pages from there.

preview

def on_preview(self, preview: PrintOperationPreview, context: PrintContext, parent: Window | None) -> bool: ...

Gets emitted when a preview is requested from the native dialog.

The default handler for this signal uses an external viewer application to preview.

To implement a custom print preview, an application must return True from its handler for this signal. In order to use the provided context for the preview implementation, it must be given a suitable cairo context with PrintContext.set_cairo_context.

The custom preview implementation can use PrintOperationPreview.is_selected and PrintOperationPreview.render_page to find pages which are selected for print and render them. The preview must be finished by calling PrintOperationPreview.end_preview (typically in response to the user clicking a close button).

request-page-setup

def on_request_page_setup(self, context: PrintContext, page_nr: int, setup: PageSetup) -> None: ...

Emitted once for every page that is printed.

This gives the application a chance to modify the page setup. Any changes done to setup will be in force only for printing this page.

status-changed

def on_status_changed(self) -> None: ...

Emitted at between the various phases of the print operation.

See PrintStatus for the phases that are being discriminated. Use PrintOperation.get_status to find out the current status.

update-custom-widget

def on_update_custom_widget(self, widget: Widget, setup: PageSetup, settings: PrintSettings) -> None: ...

Emitted after change of selected printer.

The actual page setup and print settings are passed to the custom widget, which can actualize itself according to this change.