Esempio n. 1
0
    def print(self, printer=None, pageNumbers=None, showDialog=True):
        """Print the contents of the View."""
        import qpageview.poppler
        import qpageview.cupsprinter

        if printer is None:
            if self._printer is None:
                self._printer = QPrinter()
            printer = self._printer
        printer.setCopyCount(1)  # prevent embarrassing situations :-)
        if self.document() and self.document().filename():
            filename = os.path.basename(self.document().filename())
        else:
            filename = ""
        printer.setDocName(filename)
        if showDialog:
            qpageview.cupsprinter.clearPageSetSetting(printer)
            dlg = QPrintDialog(printer, self)
            if filename:
                title = app.caption(
                    _("Print {filename}").format(filename=filename))
            else:
                title = app.caption(_("Print"))
            dlg.setWindowTitle(title)
            dlg.setMinMax(1, self.pageCount())
            if not dlg.exec_():
                return  # cancelled
        s = QSettings()
        printer.setResolution(s.value("printing/dpi", 300, int))

        # is it possible and preferred to print a PDF directly with cups?
        # on Mac, when printing directly with cups, the system print window is shown
        # but its settings are ignored and any choice (including opening the PDF)
        # results in printing to cups' default printer
        if (s.value("printing/directcups",
                    False if sys.platform.startswith('darwin') else True, bool)
                and isinstance(self.document(),
                               qpageview.poppler.PopplerDocument)
                and os.path.isfile(self.document().filename())
                and not printer.outputFileName()):
            h = qpageview.cupsprinter.handle(printer)
            if h:
                if not h.printFile(self.document().filename()):
                    QMessageBox.warning(
                        self, _("Printing Error"), "{0}\n{1}".format(
                            _("An error occurred (code: {num}):").format(
                                num=h.status), h.error))
                return
        job = super().print(printer, pageNumbers, False)
        if job:
            progress = PrintProgressDialog(job, self)
            progress.setWindowTitle(title)
            progress.setLabelText(_("Preparing to print..."))
            progress.show()
Esempio n. 2
0
    def print(self, printer=None, pageNumbers=None, showDialog=True):
        """Print all, or speficied pages to QPrinter printer.

        If given the pageNumbers should be a list containing page numbers
        starting with 1. If showDialog is True, a print dialog is shown, and
        printing is canceled when the user cancels the dialog.

        If the QPrinter to use is not specified, a default one is created.
        The print job is started and returned (a printing.PrintJob instance),
        so signals for monitoring the progress could be connected to. (If the
        user cancels the dialog, no print job is returned.)

        """
        if printer is None:
            printer = QPrinter()
            printer.setResolution(300)
        if showDialog:
            dlg = QPrintDialog(printer, self)
            dlg.setMinMax(1, self.pageCount())
            if not dlg.exec_():
                return  # cancelled
        if not pageNumbers:
            if printer.printRange() == QPrinter.CurrentPage:
                pageNumbers = [self.currentPageNumber()]
            else:
                if printer.printRange() == QPrinter.PageRange:
                    first = printer.toPage() or 1
                    last = printer.fromPage() or self.pageCount()
                else:
                    first, last = 1, self.pageCount()
                pageNumbers = list(range(first, last + 1))
            if printer.pageOrder() == QPrinter.LastPageFirst:
                pageNumbers.reverse()
        # add the page objects
        pageList = [(n, self.page(n)) for n in pageNumbers]
        from . import printing
        job = printing.PrintJob(printer, pageList)
        job.start()
        return job
Esempio n. 3
0
def print_(doc, filename=None, widget=None):
    """Prints the popplerqt5.Poppler.Document.
    
    The filename is used in the dialog and print job name.
    If the filename is not given, it defaults to a translation of "PDF Document".
    The widget is a widget to use as parent for the print dialog etc.
    
    """
    # Decide how we will print.
    # on Windows and Mac OS X a print command must be specified, otherwise
    # we'll use raster printing
    s = QSettings()
    s.beginGroup("helper_applications")
    cmd = s.value("printcommand", "", str)
    use_dialog = s.value("printcommand/dialog", False, bool)
    resolution = s.value("printcommand/dpi", 300, int)
    linux_lpr = False
    
    if os.name != 'nt' and not sys.platform.startswith('darwin'):
        # we're probably on Linux
        if not cmd:
            cmd = fileprinter.lprCommand()
            if cmd:
                linux_lpr = True
        elif cmd.split('/')[-1] in fileprinter.lpr_commands:
            linux_lpr = True

    print_file = filename
    title = os.path.basename(filename) if filename else _("PDF Document")
    
    if widget:
        try:
            printer = _printers[widget]
        except KeyError:
            printer = _printers[widget] = QPrinter()
        else:
            printer.setCopyCount(1)
    else:
        printer = QPrinter()
    
    printer.setDocName(title)
    printer.setPrintRange(QPrinter.AllPages)
    
    if linux_lpr or use_dialog or not cmd:
        dlg = QPrintDialog(printer, widget)
        dlg.setMinMax(1, doc.numPages())
        dlg.setOption(QPrintDialog.PrintToFile, False)
        dlg.setWindowTitle(app.caption(_("Print {filename}").format(filename=title)))
        
        result = dlg.exec_()
        if widget:
            dlg.deleteLater() # because it has a parent
        if not result:
            return # cancelled
    
    if linux_lpr or '$ps' in cmd:
        # make a PostScript file with the desired paper size
        ps = QTemporaryFile()
        if ps.open() and qpopplerview.printer.psfile(doc, printer, ps):
            ps.close()
            print_file = ps.fileName()
    elif cmd:
        if printer.printRange() != QPrinter.AllPages:
            cmd = None # we can't cut out pages from a PDF file
        elif '$pdf' not in cmd:
            cmd += ' $pdf'
    
    command = []
    if linux_lpr:
        # let all converted pages print
        printer.setPrintRange(QPrinter.AllPages)
        command = fileprinter.printCommand(cmd, printer, ps.fileName())
    elif cmd and print_file:
        for arg in helpers.shell_split(cmd):
            if arg in ('$ps', '$pdf'):
                command.append(print_file)
            else:
                arg = arg.replace('$printer', printer.printerName())
                command.append(arg)
    if command:
        if subprocess.call(command):
            QMessageBox.warning(widget, _("Printing Error"),
                _("Could not send the document to the printer."))
        return
    else:
        # Fall back printing of rendered raster images.
        # It is unsure if the Poppler ArthurBackend ever will be ready for
        # good rendering directly to a painter, so we'll fall back to using
        # raster images.
        
        p = Printer()
        p.setDocument(doc)
        p.setPrinter(printer)
        p.setResolution(resolution)
        
        d = QProgressDialog()
        d.setModal(True)
        d.setMinimumDuration(0)
        d.setRange(0, len(p.pageList()) + 1)
        d.canceled.connect(p.abort)
        
        def progress(num, total, page):
            d.setValue(num)
            d.setLabelText(_("Printing page {page} ({num} of {total})...").format(
                page=page, num=num, total=total))
                
        def finished():
            p.deleteLater()
            d.deleteLater()
            d.hide()
            if not p.success and not p.aborted():
                QMessageBox.warning(widget, _("Printing Error"),
                    _("Could not send the document to the printer."))
            
        p.finished.connect(finished)
        p.printing.connect(progress)
        p.start()
Esempio n. 4
0
def print_(doc, filename=None, widget=None):
    """Prints the popplerqt5.Poppler.Document.

    The filename is used in the dialog and print job name.
    If the filename is not given, it defaults to a translation of "PDF Document".
    The widget is a widget to use as parent for the print dialog etc.

    """
    # Decide how we will print.
    # on Windows and Mac OS X a print command must be specified, otherwise
    # we'll use raster printing
    s = QSettings()
    s.beginGroup("helper_applications")
    cmd = s.value("printcommand", "", str)
    use_dialog = s.value("printcommand/dialog", False, bool)
    resolution = s.value("printcommand/dpi", 300, int)
    linux_lpr = False

    if os.name != 'nt' and not sys.platform.startswith('darwin'):
        # we're probably on Linux
        if not cmd:
            cmd = fileprinter.lprCommand()
            if cmd:
                linux_lpr = True
        elif cmd.split('/')[-1] in fileprinter.lpr_commands:
            linux_lpr = True

    print_file = filename
    title = os.path.basename(filename) if filename else _("PDF Document")

    if widget:
        try:
            printer = _printers[widget]
        except KeyError:
            printer = _printers[widget] = QPrinter()
        else:
            printer.setCopyCount(1)
    else:
        printer = QPrinter()

    printer.setDocName(title)
    printer.setPrintRange(QPrinter.AllPages)

    if linux_lpr or use_dialog or not cmd:
        dlg = QPrintDialog(printer, widget)
        dlg.setMinMax(1, doc.numPages())
        dlg.setOption(QPrintDialog.PrintToFile, False)
        dlg.setWindowTitle(
            app.caption(_("Print {filename}").format(filename=title)))

        result = dlg.exec_()
        if widget:
            dlg.deleteLater()  # because it has a parent
        if not result:
            return  # cancelled

    if linux_lpr or '$ps' in cmd:
        # make a PostScript file with the desired paper size
        ps = QTemporaryFile()
        if ps.open() and qpopplerview.printer.psfile(doc, printer, ps):
            ps.close()
            print_file = ps.fileName()
    elif cmd:
        if printer.printRange() != QPrinter.AllPages:
            cmd = None  # we can't cut out pages from a PDF file
        elif '$pdf' not in cmd:
            cmd += ' $pdf'

    command = []
    if linux_lpr:
        # let all converted pages print
        printer.setPrintRange(QPrinter.AllPages)
        command = fileprinter.printCommand(cmd, printer, ps.fileName())
    elif cmd and print_file:
        for arg in helpers.shell_split(cmd):
            if arg in ('$ps', '$pdf'):
                command.append(print_file)
            else:
                arg = arg.replace('$printer', printer.printerName())
                command.append(arg)
    if command:
        if subprocess.call(command):
            QMessageBox.warning(
                widget, _("Printing Error"),
                _("Could not send the document to the printer."))
        return
    else:
        # Fall back printing of rendered raster images.
        # It is unsure if the Poppler ArthurBackend ever will be ready for
        # good rendering directly to a painter, so we'll fall back to using
        # raster images.

        p = Printer()
        p.setDocument(doc)
        p.setPrinter(printer)
        p.setResolution(resolution)

        d = QProgressDialog()
        d.setModal(True)
        d.setMinimumDuration(0)
        d.setRange(0, len(p.pageList()) + 1)
        d.canceled.connect(p.abort)

        def progress(num, total, page):
            d.setValue(num)
            d.setLabelText(
                _("Printing page {page} ({num} of {total})...").format(
                    page=page, num=num, total=total))

        def finished():
            p.deleteLater()
            d.deleteLater()
            d.hide()
            if not p.success and not p.aborted():
                QMessageBox.warning(
                    widget, _("Printing Error"),
                    _("Could not send the document to the printer."))

        p.finished.connect(finished)
        p.printing.connect(progress)
        p.start()