python Gtk.PrintOperation打印pdf

时间:2015-02-04 15:46:57

标签: python gtk3 pyobject

到目前为止,我正在使用此代码的变体来打印我用pisa创建的pdf。

取自pygtk faq:

import gtk
import gtkunixprint

def print_cb(printjob, data, errormsg):
    if errormsg:
        print('Error occurred while printing:\n%s' % errormsg)

filename = 'the_pdf_file_to_be_printed.pdf'
pud = gtkunixprint.PrintUnixDialog()
response = pud.run()
if response == gtk.RESPONSE_OK:
    printer = pud.get_selected_printer()
    settings = pud.get_settings()
    setup = pud.get_page_setup()
    printjob = gtkunixprint.PrintJob('Printing %s' % filename, printer, settings, setup)
    printjob.set_source_file(filename)
    printjob.send(print_cb)
pud.destroy()

现在我移植到Gtk3 PyObject,我无法解决问题。 我发现Gtk.PrintOperation是一种方式,但我不能将打印操作与printJob相关联或如何将文件传递给打印。
谢谢

1 个答案:

答案 0 :(得分:5)

这是一个例子,我希望你发现它很有用

#!/usr/bin/env python
import os
import sys
from gi.repository import GLib, Gtk, Poppler


class PrintingApp:
    def __init__(self, file_uri):
        self.operation = Gtk.PrintOperation()

        self.operation.connect('begin-print', self.begin_print, None)
        self.operation.connect('draw-page', self.draw_page, None)

        self.doc = Poppler.Document.new_from_file(file_uri)

    def begin_print(self, operation, print_ctx, print_data):
        operation.set_n_pages(self.doc.get_n_pages())

    def draw_page(self, operation, print_ctx, page_num, print_data):
        cr = print_ctx.get_cairo_context()
        page = self.doc.get_page(page_num)
        page.render(cr)

    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 main():
    if len(sys.argv) != 2:
        print "%s FILE" % sys.argv[0]
        sys.exit(1)

    file_uri = GLib.filename_to_uri(os.path.abspath(sys.argv[1]))

    main_window = Gtk.OffscreenWindow()
    app = PrintingApp(file_uri)
    GLib.idle_add(app.run, main_window)
    Gtk.main()

if __name__ == '__main__':
    main()