PyGobject(八十七)Gtk.PrintOperation

Gtk.PrintOperation

打印机的操作方法
这里写图片描述

Methods

方法修饰词方法名及参数
staticnew ()
cancel ()
draw_page_finish ()
get_default_page_setup ()
get_embed_page_setup ()
get_error ()
get_has_selection ()
get_n_pages_to_print ()
get_print_settings ()
get_status ()
get_status_string ()
get_support_selection ()
is_finished ()
run (action, parent)
set_allow_async (allow_async)
set_current_page (current_page)
set_custom_tab_label (label)
set_default_page_setup (default_page_setup)
set_defer_drawing ()
set_embed_page_setup (embed)
set_export_filename (filename)
set_has_selection (has_selection)
set_job_name (job_name)
set_n_pages (n_pages)
set_print_settings (print_settings)
set_show_progress (show_progress)
set_support_selection (support_selection)
set_track_print_status (track_status)
set_unit (unit)
set_use_full_page (full_page)

Virtual Methods

do_begin_print (context)
do_custom_widget_apply (widget)
do_done (result)
do_draw_page (context, page_nr)
do_end_print (context)
do_paginate (context)
do_preview (preview, context, parent)
do_request_page_setup (context, page_nr, setup)
do_status_changed ()
do_update_custom_widget (widget, setup, settings)

Properties

NameTypeFlagsShort Description
allow-asyncboolr/w/enTrue if print process may run asynchronous.
current-pageintr/w/enThe current page in the document
custom-tab-labelstrr/wLabel for the tab containing custom widgets.
default-page-setupGtk.PageSetupr/wThe Gtk.PageSetup used by default
embed-page-setupboolr/w/enTrue if page setup combos are embedded in GtkPrintUnixDialog
export-filenamestrr/wExport filename
has-selectionboolr/w/enTrue if a selection exists.
job-namestrr/wA string used for identifying the print job.
n-pagesintr/w/enThe number of pages in the document.
n-pages-to-printintr/enThe number of pages that will be printed.
print-settingsGtk.PrintSettingsr/wThe Gtk.PrintSettings used for initializing the dialog
show-progressboolr/w/enTrue if a progress dialog is shown while printing.
statusGtk.PrintStatusr/enThe status of the print operation
status-stringstrrA human-readable description of the status
support-selectionboolr/w/enTrue if the print operation will support print of selection.
track-print-statusboolr/w/enTrue if the print operation will continue to report on the print job status after the print data has been sent to the printer or print server.
unitGtk.Unitr/w/enThe unit in which distances can be measured in the context
use-full-pageboolr/w/enTrue if the origin of the context should be at the corner of the page and not the corner of the imageable area

Signals

NameShort Description
begin-printEmitted after the user has finished changing print settings in the dialog, before the actual rendering starts.
create-custom-widgetEmitted when displaying the print dialog.
custom-widget-applyEmitted right before Gtk.PrintOperation ::begin-print if you added a custom widget in the Gtk.PrintOperation ::create-custom-widget handler.
doneEmitted when the print operation run has finished doing everything required for printing.
draw-pageEmitted for every page that is printed.
end-printEmitted after all pages have been rendered.
paginateEmitted after the Gtk.PrintOperation ::begin-print signal, but before the actual rendering starts.
previewGets emitted when a preview is requested from the native dialog.
request-page-setupEmitted once for every page that is printed, to give the application a chance to modify the page setup.
status-changedEmitted at between the various phases of the print operation.
update-custom-widgetEmitted after change of selected printer.

Gtk.PrintSettings

打印机设置
这里写图片描述

Methods

方法修饰词方法名及参数
staticnew ()
staticnew_from_file (file_name)
staticnew_from_key_file (key_file, group_name)
copy ()
foreach (func, *user_data)
get (key)
get_bool (key)
get_collate ()
get_default_source ()
get_dither ()
get_double (key)
get_double_with_default (key, def_)
get_duplex ()
get_finishings ()
get_int (key)
get_int_with_default (key, def_)
get_length (key, unit)
get_media_type ()
get_n_copies ()
get_number_up ()
get_number_up_layout ()
get_orientation ()
get_output_bin ()
get_page_ranges ()
get_page_set ()
get_paper_height (unit)
get_paper_size ()
get_paper_width (unit)
get_print_pages ()
get_printer ()
get_printer_lpi ()
get_quality ()
get_resolution ()
get_resolution_x ()
get_resolution_y ()
get_reverse ()
get_scale ()
get_use_color ()
has_key (key)
load_file (file_name)
load_key_file (key_file, group_name)
set (key, value)
set_bool (key, value)
set_collate (collate)
set_default_source (default_source)
set_dither (dither)
set_double (key, value)
set_duplex (duplex)
set_finishings (finishings)
set_int (key, value)
set_length (key, value, unit)
set_media_type (media_type)
set_n_copies (num_copies)
set_number_up (number_up)
set_number_up_layout (number_up_layout)
set_orientation (orientation)
set_output_bin (output_bin)
set_page_ranges (page_ranges)
set_page_set (page_set)
set_paper_height (height, unit)
set_paper_size (paper_size)
set_paper_width (width, unit)
set_print_pages (pages)
set_printer (printer)
set_printer_lpi (lpi)
set_quality (quality)
set_resolution (resolution)
set_resolution_xy (resolution_x, resolution_y)
set_reverse (reverse)
set_scale (scale)
set_use_color (use_color)
to_file (file_name)
to_key_file (key_file, group_name)
unset (key)

Virtual Methods

Properties

NameTypeFlagsShort Description

Signals

NameShort Description

Gtk.PageSetup

打印机设置
这里写图片描述

Methods

方法修饰词方法名及参数
staticnew ()
staticnew_from_file (file_name)
staticnew_from_key_file (key_file, group_name)
copy ()
get_bottom_margin (unit)
get_left_margin (unit)
get_orientation ()
get_page_height (unit)
get_page_width (unit)
get_paper_height (unit)
get_paper_size ()
get_paper_width (unit)
get_right_margin (unit)
get_top_margin (unit)
load_file (file_name)
load_key_file (key_file, group_name)
set_bottom_margin (margin, unit)
set_left_margin (margin, unit)
set_orientation (orientation)
set_paper_size (size)
set_paper_size_and_default_margins (size)
set_right_margin (margin, unit)
set_top_margin (margin, unit)
to_file (file_name)
to_key_file (key_file, group_name)

Virtual Methods

Properties

NameTypeFlagsShort Description

Signals

NameShort Description

例子

Gtk.PageSetup

这里写图片描述
代码:

#!/usr/bin/env python3
# Created by xiaosanyu at 16/7/19
# section 136
# 
# author: xiaosanyu
# website: yuxiaosan.tk \
#          http://blog.csdn.net/a87b01c14
# created: 16/7/19

TITLE = "PageSetup"
DESCRIPTION = """
PageSetupDialog can be used if page setup is needed
independent of a full printing dialog.
"""
import gi

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk


def main():
    page_setup = Gtk.PageSetup()
    settings = Gtk.PrintSettings()

    new_page_setup = Gtk.print_run_page_setup_dialog(None, page_setup, settings)


if __name__ == "__main__":
    main()

这里写图片描述
这里写图片描述

代码:

#!/usr/bin/env python3
# section 137
TITLE = "Printing"
DESCRIPTION = """
GtkPrintOperation offers a simple API to support printing in a cross-platform way.
"""
import gi

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

from gi.repository import Gtk, GLib, Pango, PangoCairo
import math
import os


class PrintingApp:
    HEADER_HEIGHT = 10 * 72 / 25.4
    HEADER_GAP = 3 * 72 / 25.4

    def __init__(self):
        self.operation = Gtk.PrintOperation()
        print_data = {'filename': os.path.abspath(__file__),
                      'font_size': 12.0,
                      'lines_per_page': 0,
                      'lines': None,
                      'num_lines': 0,
                      'num_pages': 0
                      }

        self.operation.connect('begin-print', self.begin_print, print_data)
        self.operation.connect('draw-page', self.draw_page, print_data)
        self.operation.connect('end-print', self.end_print, print_data)

        self.operation.set_use_full_page(False)
        self.operation.set_unit(Gtk.Unit.POINTS)
        self.operation.set_embed_page_setup(True)

        settings = Gtk.PrintSettings()

        dir = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_DOCUMENTS)
        if dir is None:
            dir = GLib.get_home_dir()
        if settings.get(Gtk.PRINT_SETTINGS_OUTPUT_FILE_FORMAT) == 'ps':
            ext = '.ps'
        elif settings.get(Gtk.PRINT_SETTINGS_OUTPUT_FILE_FORMAT) == 'svg':
            ext = '.svg'
        else:
            ext = '.pdf'

        uri = "file://%s/gtk-demo%s" % (dir, ext)
        settings.set(Gtk.PRINT_SETTINGS_OUTPUT_URI, uri)
        self.operation.set_print_settings(settings)

    def run(self, parent=None):
        result = self.operation.run(Gtk.PrintOperationAction.PRINT_DIALOG, parent)

        if result == Gtk.PrintOperationResult.ERROR:
            message = self.operation.get_error()

            dialog = Gtk.MessageDialog(parent,
                                       0,
                                       Gtk.MessageType.ERROR,
                                       Gtk.ButtonsType.CLOSE,
                                       message)

            dialog.run()
            dialog.destroy()

        Gtk.main_quit()

    def begin_print(self, operation, print_ctx, print_data):
        height = print_ctx.get_height() - self.HEADER_HEIGHT - self.HEADER_GAP
        print_data['lines_per_page'] = \
            math.floor(height / print_data['font_size'])

        file_path = print_data['filename']
        if not os.path.isfile(file_path):
            file_path = os.path.join('demos', file_path)
            if not os.path.isfile:
                raise Exception("file not found: " % (file_path,))

        # in reality you should most likely not read the entire
        # file into a buffer
        source_file = open(file_path, 'r')
        s = source_file.read()
        print_data['lines'] = s.split('\n')

        print_data['num_lines'] = len(print_data['lines'])
        print_data['num_pages'] = \
            (print_data['num_lines'] - 1) / print_data['lines_per_page'] + 1

        operation.set_n_pages(print_data['num_pages'])

    def draw_page(self, operation, print_ctx, page_num, print_data):
        cr = print_ctx.get_cairo_context()
        width = print_ctx.get_width()

        cr.rectangle(0, 0, width, self.HEADER_HEIGHT)
        cr.set_source_rgb(0.8, 0.8, 0.8)
        cr.fill_preserve()

        cr.set_source_rgb(0, 0, 0)
        cr.set_line_width(1)
        cr.stroke()

        layout = print_ctx.create_pango_layout()
        desc = Pango.FontDescription('sans 14')
        layout.set_font_description(desc)

        layout.set_text(print_data['filename'], -1)
        (text_width, text_height) = layout.get_pixel_size()

        if text_width > width:
            layout.set_width(width)
            layout.set_ellipsize(Pango.EllipsizeMode.START)
            (text_width, text_height) = layout.get_pixel_size()

        cr.move_to((width - text_width) / 2,
                   (self.HEADER_HEIGHT - text_height) / 2)
        PangoCairo.show_layout(cr, layout)

        page_str = "%d/%d" % (page_num + 1, print_data['num_pages'])
        layout.set_text(page_str, -1)

        layout.set_width(-1)
        (text_width, text_height) = layout.get_pixel_size()
        cr.move_to(width - text_width - 4,
                   (self.HEADER_HEIGHT - text_height) / 2)
        PangoCairo.show_layout(cr, layout)

        layout = print_ctx.create_pango_layout()

        desc = Pango.FontDescription('monospace')
        desc.set_size(print_data['font_size'] * Pango.SCALE)
        layout.set_font_description(desc)

        cr.move_to(0, self.HEADER_HEIGHT + self.HEADER_GAP)
        lines_pp = int(print_data['lines_per_page'])
        num_lines = print_data['num_lines']
        data_lines = print_data['lines']
        font_size = print_data['font_size']
        line = page_num * lines_pp

        for i in range(lines_pp):
            if line >= num_lines:
                break

            layout.set_text(data_lines[line], -1)
            PangoCairo.show_layout(cr, layout)
            cr.rel_move_to(0, font_size)
            line += 1

    def end_print(self, operation, print_ctx, print_data):
        pass


def main():
    app = PrintingApp()
    GLib.idle_add(app.run, None)
    Gtk.main()


if __name__ == '__main__':
    main()





代码下载地址:http://download.csdn.net/detail/a87b01c14/9594728

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sanxiaochengyu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值