Beispiel #1
0
 def __call__(self, ok):
     from PyQt4.Qt import QImage, QPainter, QByteArray, QBuffer
     try:
         if not ok:
             raise RuntimeError('Rendering of HTML failed.')
         de = self.page.mainFrame().documentElement()
         pe = de.findFirst('parsererror')
         if not pe.isNull():
             raise ParserError(pe.toPlainText())
         image = QImage(self.page.viewportSize(), QImage.Format_ARGB32)
         image.setDotsPerMeterX(96*(100/2.54))
         image.setDotsPerMeterY(96*(100/2.54))
         painter = QPainter(image)
         self.page.mainFrame().render(painter)
         painter.end()
         ba = QByteArray()
         buf = QBuffer(ba)
         buf.open(QBuffer.WriteOnly)
         image.save(buf, 'JPEG')
         self.data = str(ba.data())
     except Exception as e:
         self.exception = e
         self.traceback = traceback.format_exc()
     finally:
         self.loop.exit(0)
Beispiel #2
0
 def render_emblems(item, emblems):
     emblems = tuple(emblems)
     if not emblems:
         return
     icon = self.rendered_emblem_cache.get(emblems, None)
     if icon is None:
         pixmaps = []
         for emblem in emblems:
             pm = self.emblem_cache.get(emblem, None)
             if pm is None:
                 pm = self.emblem_cache[emblem] = QPixmap(
                     I(emblem)).scaled(self.iconSize(), transformMode=Qt.SmoothTransformation)
             pixmaps.append(pm)
         num = len(pixmaps)
         w, h = pixmaps[0].width(), pixmaps[0].height()
         if num == 1:
             icon = self.rendered_emblem_cache[emblems] = QIcon(pixmaps[0])
         else:
             canvas = QPixmap((num * w) + ((num-1)*2), h)
             canvas.fill(Qt.transparent)
             painter = QPainter(canvas)
             for i, pm in enumerate(pixmaps):
                 painter.drawPixmap(i * (w + 2), 0, pm)
             painter.end()
             icon = self.rendered_emblem_cache[emblems] = canvas
     item.setData(0, Qt.DecorationRole, icon)
Beispiel #3
0
 def paintEvent(self, event):
     painter = QPainter(self)
     painter.setRenderHints(self.renderHints())
     self.document.mainFrame().render(painter, event.region())
     if not self.isEnabled():
         painter.fillRect(event.region().boundingRect(), self.DISABLED_BRUSH)
     painter.end()
Beispiel #4
0
 def paintEvent(self, event):
     canvas_size = self.rect()
     width = self.current_pixmap_size.width()
     extrax = canvas_size.width() - width
     if extrax < 0:
         extrax = 0
     x = int(extrax/2.)
     height = self.current_pixmap_size.height()
     extray = canvas_size.height() - height
     if extray < 0:
         extray = 0
     y = int(extray/2.)
     target = QRect(x, y, width, height)
     p = QPainter(self)
     p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
     p.drawPixmap(target, self.pixmap.scaled(target.size(),
         Qt.KeepAspectRatio, Qt.SmoothTransformation))
     if gprefs['bd_overlay_cover_size']:
         sztgt = target.adjusted(0, 0, 0, -4)
         f = p.font()
         f.setBold(True)
         p.setFont(f)
         sz = u'\u00a0%d x %d\u00a0'%(self.pixmap.width(), self.pixmap.height())
         flags = Qt.AlignBottom|Qt.AlignRight|Qt.TextSingleLine
         szrect = p.boundingRect(sztgt, flags, sz)
         p.fillRect(szrect.adjusted(0, 0, 0, 4), QColor(0, 0, 0, 200))
         p.setPen(QPen(QColor(255,255,255)))
         p.drawText(sztgt, flags, sz)
     p.end()
Beispiel #5
0
def drag_icon(self, cover, multiple):
    cover = cover.scaledToHeight(120, Qt.SmoothTransformation)
    if multiple:
        base_width = cover.width()
        base_height = cover.height()
        base = QImage(base_width+21, base_height+21,
                QImage.Format_ARGB32_Premultiplied)
        base.fill(QColor(255, 255, 255, 0).rgba())
        p = QPainter(base)
        rect = QRect(20, 0, base_width, base_height)
        p.fillRect(rect, QColor('white'))
        p.drawRect(rect)
        rect.moveLeft(10)
        rect.moveTop(10)
        p.fillRect(rect, QColor('white'))
        p.drawRect(rect)
        rect.moveLeft(0)
        rect.moveTop(20)
        p.fillRect(rect, QColor('white'))
        p.save()
        p.setCompositionMode(p.CompositionMode_SourceAtop)
        p.drawImage(rect.topLeft(), cover)
        p.restore()
        p.drawRect(rect)
        p.end()
        cover = base
    return QPixmap.fromImage(cover)
Beispiel #6
0
def drag_icon(self, cover, multiple):
    cover = cover.scaledToHeight(120, Qt.SmoothTransformation)
    if multiple:
        base_width = cover.width()
        base_height = cover.height()
        base = QImage(base_width + 21, base_height + 21,
                      QImage.Format_ARGB32_Premultiplied)
        base.fill(QColor(255, 255, 255, 0).rgba())
        p = QPainter(base)
        rect = QRect(20, 0, base_width, base_height)
        p.fillRect(rect, QColor('white'))
        p.drawRect(rect)
        rect.moveLeft(10)
        rect.moveTop(10)
        p.fillRect(rect, QColor('white'))
        p.drawRect(rect)
        rect.moveLeft(0)
        rect.moveTop(20)
        p.fillRect(rect, QColor('white'))
        p.save()
        p.setCompositionMode(p.CompositionMode_SourceAtop)
        p.drawImage(rect.topLeft(), cover)
        p.restore()
        p.drawRect(rect)
        p.end()
        cover = base
    return QPixmap.fromImage(cover)
Beispiel #7
0
 def render_html(self, ok):
     try:
         if not ok:
             return
         cwidth, cheight = self.page.mainFrame().contentsSize().width(), self.page.mainFrame().contentsSize().height()
         self.page.setViewportSize(QSize(cwidth, cheight))
         factor = float(self.width)/cwidth if cwidth > self.width else 1
         cutoff_height = int(self.height/factor)-3
         image = QImage(self.page.viewportSize(), QImage.Format_ARGB32)
         image.setDotsPerMeterX(self.dpi*(100/2.54))
         image.setDotsPerMeterY(self.dpi*(100/2.54))
         painter = QPainter(image)
         self.page.mainFrame().render(painter)
         painter.end()
         cheight = image.height()
         cwidth = image.width()
         pos = 0
         while pos < cheight:
             img = image.copy(0, pos, cwidth, min(cheight-pos, cutoff_height))
             pos += cutoff_height-20
             if cwidth > self.width:
                 img = img.scaledToWidth(self.width, Qt.SmoothTransform)
             f = os.path.join(self.tdir, '%d.png'%pos)
             img.save(f)
             self.images.append((f, img.width(), img.height()))
     finally:
         QApplication.quit()
Beispiel #8
0
 def __call__(self, ok):
     from PyQt4.Qt import QImage, QPainter, QByteArray, QBuffer
     try:
         if not ok:
             raise RuntimeError('Rendering of HTML failed.')
         de = self.page.mainFrame().documentElement()
         pe = de.findFirst('parsererror')
         if not pe.isNull():
             raise ParserError(pe.toPlainText())
         image = QImage(self.page.viewportSize(), QImage.Format_ARGB32)
         image.setDotsPerMeterX(96*(100/2.54))
         image.setDotsPerMeterY(96*(100/2.54))
         painter = QPainter(image)
         self.page.mainFrame().render(painter)
         painter.end()
         ba = QByteArray()
         buf = QBuffer(ba)
         buf.open(QBuffer.WriteOnly)
         image.save(buf, 'JPEG')
         self.data = str(ba.data())
     except Exception as e:
         self.exception = e
         self.traceback = traceback.format_exc()
     finally:
         self.loop.exit(0)
 def render_emblems(item, emblems):
     emblems = tuple(emblems)
     if not emblems:
         return
     icon = self.rendered_emblem_cache.get(emblems, None)
     if icon is None:
         pixmaps = []
         for emblem in emblems:
             pm = self.emblem_cache.get(emblem, None)
             if pm is None:
                 pm = self.emblem_cache[emblem] = QPixmap(
                     I(emblem)).scaled(
                         self.iconSize(),
                         transformMode=Qt.SmoothTransformation)
             pixmaps.append(pm)
         num = len(pixmaps)
         w, h = pixmaps[0].width(), pixmaps[0].height()
         if num == 1:
             icon = self.rendered_emblem_cache[emblems] = QIcon(
                 pixmaps[0])
         else:
             canvas = QPixmap((num * w) + ((num - 1) * 2), h)
             canvas.fill(Qt.transparent)
             painter = QPainter(canvas)
             for i, pm in enumerate(pixmaps):
                 painter.drawPixmap(i * (w + 2), 0, pm)
             painter.end()
             icon = self.rendered_emblem_cache[emblems] = canvas
     item.setData(0, Qt.DecorationRole, icon)
Beispiel #10
0
 def paintEvent(self, ev):
     p = QPainter(self)
     p.setRenderHints(p.Antialiasing)
     p.setBrush(self.brush)
     p.setPen(Qt.NoPen)
     p.drawPath(self.arrow_path)
     p.end()
Beispiel #11
0
 def _exportImageToPNG(self, filename=None):
     if not filename:
         if not self._export_png_dialog:
             dialog = self._export_png_dialog = QFileDialog(self, "Export image to PNG", ".", "*.png")
             dialog.setDefaultSuffix("png")
             dialog.setFileMode(QFileDialog.AnyFile)
             dialog.setAcceptMode(QFileDialog.AcceptSave)
             dialog.setModal(True)
             QObject.connect(dialog, SIGNAL("filesSelected(const QStringList &)"), self._exportImageToPNG)
         return self._export_png_dialog.exec_() == QDialog.Accepted
     busy = BusyIndicator()
     if isinstance(filename, QStringList):
         filename = filename[0]
     filename = str(filename)
     # make QPixmap
     nx, ny = self.image.imageDims()
     (l0, l1), (m0, m1) = self.image.getExtents()
     pixmap = QPixmap(nx, ny)
     painter = QPainter(pixmap)
     # use QwtPlot implementation of draw canvas, since we want to avoid caching
     xmap = QwtScaleMap()
     xmap.setPaintInterval(0, nx)
     xmap.setScaleInterval(l1, l0)
     ymap = QwtScaleMap()
     ymap.setPaintInterval(ny, 0)
     ymap.setScaleInterval(m0, m1)
     self.image.draw(painter, xmap, ymap, pixmap.rect())
     painter.end()
     # save to file
     try:
         pixmap.save(filename, "PNG")
     except Exception as exc:
         self.emit(SIGNAL("showErrorMessage"), "Error writing %s: %s" % (filename, str(exc)))
         return
     self.emit(SIGNAL("showMessage"), "Exported image to file %s" % filename)
Beispiel #12
0
        def paintEvent(self, event):
            contents_y = self.edit.verticalScrollBar().value()
            page_bottom = contents_y + self.edit.viewport().height()
            font_metrics = self.fontMetrics()

            painter = QPainter(self)

            line_count = 0

            # Iterate over all text blocks in the document.
            block = self.edit.document().begin()

            while block.isValid():
                line_count += 1

                # The top left position of the block in the document
                position = self.edit.document().documentLayout().blockBoundingRect(block).topLeft()

                # Check if the position of the block is out side of the visible
                # area.
                if position.y() > page_bottom:
                    break

                # Draw the line number right justified at the y position of the
                # line. 3 is a magic padding number. drawText(x, y, text).
                painter.drawText(-5 + self.width() - font_metrics.width(str(line_count)) - 3, round(position.y()) - contents_y + font_metrics.ascent(), str(line_count))

                block = block.next()

            self.highest_line = line_count
            painter.end()

            QWidget.paintEvent(self, event)
Beispiel #13
0
 def paintEvent(self, ev):
     p = QPainter(self)
     p.setRenderHints(p.Antialiasing)
     p.setBrush(self.brush)
     p.setPen(Qt.NoPen)
     p.drawPath(self.arrow_path)
     p.end()
Beispiel #14
0
 def paintEvent(self, event):
     QWidget.paintEvent(self, event)
     pmap = self._pixmap
     if pmap.isNull():
         return
     w, h = pmap.width(), pmap.height()
     cw, ch = self.rect().width(), self.rect().height()
     scaled, nw, nh = fit_image(w, h, cw, ch)
     if scaled:
         pmap = pmap.scaled(nw, nh, Qt.IgnoreAspectRatio,
                 Qt.SmoothTransformation)
     w, h = pmap.width(), pmap.height()
     x = int(abs(cw - w)/2.)
     y = int(abs(ch - h)/2.)
     target = QRect(x, y, w, h)
     p = QPainter(self)
     p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
     p.drawPixmap(target, pmap)
     pen = QPen()
     pen.setWidth(self.BORDER_WIDTH)
     p.setPen(pen)
     if self.draw_border:
         p.drawRect(target)
     #p.drawRect(self.rect())
     p.end()
Beispiel #15
0
 def paintEvent(self, event):
     QWidget.paintEvent(self, event)
     pmap = self._pixmap
     if pmap.isNull():
         return
     w, h = pmap.width(), pmap.height()
     ow, oh = w, h
     cw, ch = self.rect().width(), self.rect().height()
     scaled, nw, nh = fit_image(w, h, cw, ch)
     if scaled:
         pmap = pmap.scaled(nw, nh, Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
     w, h = pmap.width(), pmap.height()
     x = int(abs(cw - w) / 2.0)
     y = int(abs(ch - h) / 2.0)
     target = QRect(x, y, w, h)
     p = QPainter(self)
     p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
     p.drawPixmap(target, pmap)
     if self.draw_border:
         pen = QPen()
         pen.setWidth(self.BORDER_WIDTH)
         p.setPen(pen)
         p.drawRect(target)
     if self.show_size:
         sztgt = target.adjusted(0, 0, 0, -4)
         f = p.font()
         f.setBold(True)
         p.setFont(f)
         sz = u"\u00a0%d x %d\u00a0" % (ow, oh)
         flags = Qt.AlignBottom | Qt.AlignRight | Qt.TextSingleLine
         szrect = p.boundingRect(sztgt, flags, sz)
         p.fillRect(szrect.adjusted(0, 0, 0, 4), QColor(0, 0, 0, 200))
         p.setPen(QPen(QColor(255, 255, 255)))
         p.drawText(sztgt, flags, sz)
     p.end()
Beispiel #16
0
    def paintEvent(self, event):
        pmap = self.blank if self.pixmap is None or self.pixmap.isNull(
        ) else self.pixmap
        target = self.rect()
        scaled, width, height = fit_image(pmap.width(), pmap.height(),
                                          target.width(), target.height())
        target.setRect(target.x(), target.y(), width, height)
        p = QPainter(self)
        p.setRenderHints(QPainter.Antialiasing
                         | QPainter.SmoothPixmapTransform)
        p.drawPixmap(target, pmap)

        if self.pixmap is not None and not self.pixmap.isNull():
            sztgt = target.adjusted(0, 0, 0, -4)
            f = p.font()
            f.setBold(True)
            p.setFont(f)
            sz = u'\u00a0%d x %d\u00a0' % (self.pixmap.width(),
                                           self.pixmap.height())
            flags = Qt.AlignBottom | Qt.AlignRight | Qt.TextSingleLine
            szrect = p.boundingRect(sztgt, flags, sz)
            p.fillRect(szrect.adjusted(0, 0, 0, 4), QColor(0, 0, 0, 200))
            p.setPen(QPen(QColor(255, 255, 255)))
            p.drawText(sztgt, flags, sz)
        p.end()
Beispiel #17
0
 def paintEvent(self, event):
     QWidget.paintEvent(self, event)
     pmap = self._pixmap
     if pmap.isNull():
         return
     w, h = pmap.width(), pmap.height()
     cw, ch = self.rect().width(), self.rect().height()
     scaled, nw, nh = fit_image(w, h, cw, ch)
     if scaled:
         pmap = pmap.scaled(nw, nh, Qt.IgnoreAspectRatio,
                            Qt.SmoothTransformation)
     w, h = pmap.width(), pmap.height()
     x = int(abs(cw - w) / 2.)
     y = int(abs(ch - h) / 2.)
     target = QRect(x, y, w, h)
     p = QPainter(self)
     p.setRenderHints(QPainter.Antialiasing
                      | QPainter.SmoothPixmapTransform)
     p.drawPixmap(target, pmap)
     pen = QPen()
     pen.setWidth(self.BORDER_WIDTH)
     p.setPen(pen)
     if self.draw_border:
         p.drawRect(target)
     #p.drawRect(self.rect())
     p.end()
        def paintEvent(self, event):
            contents_y = self.edit.verticalScrollBar().value()
            page_bottom = contents_y + self.edit.viewport().height()
            font_metrics = self.fontMetrics()

            painter = QPainter(self)

            line_count = 0

            block = self.edit.document().begin()

            while block.isValid():
                line_count += 1

                # The top left position of the block in the document
                position = self.edit.document().documentLayout().blockBoundingRect(block).topLeft()

                # Check if the position of the block is out side of the visible
                # area.
                if position.y() > page_bottom:
                    break

                # Draw the line number right justified at the y position of the
                # line. 3 is a magic padding number. drawText(x, y, text).
                painter.drawText(-5 + self.width() - font_metrics.width(str(line_count)) - 3,
                                round(position.y()) - contents_y + font_metrics.ascent(),
                                str(line_count))

                block = block.next()

            self.highest_line = line_count
            painter.end()

            QWidget.paintEvent(self, event)
Beispiel #19
0
    def do_paged_render(self, outpath):
        from PyQt4.Qt import QSize, QPainter
        if self.paged_js is None:
            from calibre.utils.resources import compiled_coffeescript
            self.paged_js = compiled_coffeescript('ebooks.oeb.display.utils')
            self.paged_js += compiled_coffeescript('ebooks.oeb.display.paged')
        printer = get_pdf_printer(self.opts, output_file_name=outpath)
        painter = QPainter(printer)
        zoomx = printer.logicalDpiX()/self.view.logicalDpiX()
        zoomy = printer.logicalDpiY()/self.view.logicalDpiY()
        painter.scale(zoomx, zoomy)

        pr = printer.pageRect()
        evaljs = self.view.page().mainFrame().evaluateJavaScript
        evaljs(self.paged_js)
        self.view.page().setViewportSize(QSize(pr.width()/zoomx,
            pr.height()/zoomy))
        evaljs('''
        document.body.style.backgroundColor = "white";
        paged_display.set_geometry(1, 0, 0, 0);
        paged_display.layout();
        paged_display.fit_images();
        ''')
        mf = self.view.page().mainFrame()
        while True:
            mf.render(painter)
            nsl = evaljs('paged_display.next_screen_location()').toInt()
            if not nsl[1] or nsl[0] <= 0: break
            evaljs('window.scrollTo(%d, 0)'%nsl[0])
            printer.newPage()

        painter.end()
        printer.abort()
Beispiel #20
0
 def paintEvent(self, event):
     canvas_size = self.rect()
     width = self.current_pixmap_size.width()
     extrax = canvas_size.width() - width
     if extrax < 0: extrax = 0
     x = int(extrax / 2.)
     height = self.current_pixmap_size.height()
     extray = canvas_size.height() - height
     if extray < 0: extray = 0
     y = int(extray / 2.)
     target = QRect(x, y, width, height)
     p = QPainter(self)
     p.setRenderHints(QPainter.Antialiasing
                      | QPainter.SmoothPixmapTransform)
     p.drawPixmap(
         target,
         self.pixmap.scaled(target.size(), Qt.KeepAspectRatio,
                            Qt.SmoothTransformation))
     if gprefs['bd_overlay_cover_size']:
         sztgt = target.adjusted(0, 0, 0, -4)
         f = p.font()
         f.setBold(True)
         p.setFont(f)
         sz = u'\u00a0%d x %d\u00a0' % (self.pixmap.width(),
                                        self.pixmap.height())
         flags = Qt.AlignBottom | Qt.AlignRight | Qt.TextSingleLine
         szrect = p.boundingRect(sztgt, flags, sz)
         p.fillRect(szrect.adjusted(0, 0, 0, 4), QColor(0, 0, 0, 200))
         p.setPen(QPen(QColor(255, 255, 255)))
         p.drawText(sztgt, flags, sz)
     p.end()
Beispiel #21
0
 def paintEvent(self, event):
     painter = QPainter(self)
     painter.setRenderHints(self.renderHints())
     self.document.mainFrame().render(painter, event.region())
     if not self.isEnabled():
         painter.fillRect(event.region().boundingRect(), self.DISABLED_BRUSH)
     painter.end()
Beispiel #22
0
    def do_paged_render(self, outpath):
        from PyQt4.Qt import QSize, QPainter
        if self.paged_js is None:
            from calibre.utils.resources import compiled_coffeescript
            self.paged_js = compiled_coffeescript('ebooks.oeb.display.utils')
            self.paged_js += compiled_coffeescript('ebooks.oeb.display.paged')
        printer = get_pdf_printer(self.opts, output_file_name=outpath)
        painter = QPainter(printer)
        zoomx = printer.logicalDpiX() / self.view.logicalDpiX()
        zoomy = printer.logicalDpiY() / self.view.logicalDpiY()
        painter.scale(zoomx, zoomy)

        pr = printer.pageRect()
        evaljs = self.view.page().mainFrame().evaluateJavaScript
        evaljs(self.paged_js)
        self.view.page().setViewportSize(
            QSize(pr.width() / zoomx,
                  pr.height() / zoomy))
        evaljs('''
        document.body.style.backgroundColor = "white";
        paged_display.set_geometry(1, 0, 0, 0);
        paged_display.layout();
        paged_display.fit_images();
        ''')
        mf = self.view.page().mainFrame()
        while True:
            mf.render(painter)
            nsl = evaljs('paged_display.next_screen_location()').toInt()
            if not nsl[1] or nsl[0] <= 0: break
            evaljs('window.scrollTo(%d, 0)' % nsl[0])
            printer.newPage()

        painter.end()
        printer.abort()
Beispiel #23
0
 def render_html(self, ok):
     try:
         if not ok:
             return
         cwidth, cheight = self.page.mainFrame().contentsSize().width(
         ), self.page.mainFrame().contentsSize().height()
         self.page.setViewportSize(QSize(cwidth, cheight))
         factor = float(self.width) / cwidth if cwidth > self.width else 1
         cutoff_height = int(self.height / factor) - 3
         image = QImage(self.page.viewportSize(), QImage.Format_ARGB32)
         image.setDotsPerMeterX(self.dpi * (100 / 2.54))
         image.setDotsPerMeterY(self.dpi * (100 / 2.54))
         painter = QPainter(image)
         self.page.mainFrame().render(painter)
         painter.end()
         cheight = image.height()
         cwidth = image.width()
         pos = 0
         while pos < cheight:
             img = image.copy(0, pos, cwidth,
                              min(cheight - pos, cutoff_height))
             pos += cutoff_height - 20
             if cwidth > self.width:
                 img = img.scaledToWidth(self.width, Qt.SmoothTransform)
             f = os.path.join(self.tdir, '%d.png' % pos)
             img.save(f)
             self.images.append((f, img.width(), img.height()))
     finally:
         QApplication.quit()
Beispiel #24
0
 def event(self, e):
     if e.type() == e.Paint:
         p = QPainter(self)
         # Without this the viewport margin is rendered in QPalette::Window
         # instead of QPalette::Base
         p.fillRect(0, 0, self.padding_left+2, self.height(), self.palette().color(QPalette.Base))
         p.end()
     return QListView.event(self, e)
Beispiel #25
0
 def event(self, e):
     if e.type() == e.Paint:
         p = QPainter(self)
         # Without this the viewport margin is rendered in QPalette::Window
         # instead of QPalette::Base
         p.fillRect(0, 0, self.padding_left + 2, self.height(),
                    self.palette().color(QPalette.Base))
         p.end()
     return QListView.event(self, e)
Beispiel #26
0
 def current_page_image(self, overlap=-1):
     if overlap < 0:
         overlap = self.height()
     img = QImage(self.width(), overlap, QImage.Format_ARGB32_Premultiplied)
     painter = QPainter(img)
     painter.setRenderHints(self.renderHints())
     self.document.mainFrame().render(painter, QRegion(0, 0, self.width(), overlap))
     painter.end()
     return img
Beispiel #27
0
 def current_page_image(self, overlap=-1):
     if overlap < 0:
         overlap = self.height()
     img = QImage(self.width(), overlap, QImage.Format_ARGB32_Premultiplied)
     painter = QPainter(img)
     painter.setRenderHints(self.renderHints())
     self.document.mainFrame().render(painter, QRegion(0, 0, self.width(), overlap))
     painter.end()
     return img
Beispiel #28
0
    def add_image(self, img, cache_key):
        ref = self.get_image(cache_key)
        if ref is not None:
            return ref

        fmt = img.format()
        image = QImage(img)
        if (image.depth() == 1 and img.colorTable().size() == 2 and
            img.colorTable().at(0) == QColor(Qt.black).rgba() and
            img.colorTable().at(1) == QColor(Qt.white).rgba()):
            if fmt == QImage.Format_MonoLSB:
                image = image.convertToFormat(QImage.Format_Mono)
            fmt = QImage.Format_Mono
        else:
            if (fmt != QImage.Format_RGB32 and fmt != QImage.Format_ARGB32):
                image = image.convertToFormat(QImage.Format_ARGB32)
                fmt = QImage.Format_ARGB32

        w = image.width()
        h = image.height()
        d = image.depth()

        if fmt == QImage.Format_Mono:
            bytes_per_line = (w + 7) >> 3
            data = image.constBits().asstring(bytes_per_line * h)
            return self.write_image(data, w, h, d, cache_key=cache_key)

        has_alpha = False
        soft_mask = None

        if fmt == QImage.Format_ARGB32:
            tmask = image.constBits().asstring(4*w*h)[self.alpha_bit::4]
            sdata = bytearray(tmask)
            vals = set(sdata)
            vals.discard(255)  # discard opaque pixels
            has_alpha = bool(vals)
            if has_alpha:
                # Blend image onto a white background as otherwise Qt will render
                # transparent pixels as black
                background = QImage(image.size(), QImage.Format_ARGB32_Premultiplied)
                background.fill(Qt.white)
                painter = QPainter(background)
                painter.drawImage(0, 0, image)
                painter.end()
                image = background

        ba = QByteArray()
        buf = QBuffer(ba)
        image.save(buf, 'jpeg', 94)
        data = bytes(ba.data())

        if has_alpha:
            soft_mask = self.write_image(tmask, w, h, 8)

        return self.write_image(data, w, h, 32, dct=True,
                                soft_mask=soft_mask, cache_key=cache_key)
Beispiel #29
0
    def add_image(self, img, cache_key):
        ref = self.get_image(cache_key)
        if ref is not None:
            return ref

        fmt = img.format()
        image = QImage(img)
        if (image.depth() == 1 and img.colorTable().size() == 2 and
            img.colorTable().at(0) == QColor(Qt.black).rgba() and
            img.colorTable().at(1) == QColor(Qt.white).rgba()):
            if fmt == QImage.Format_MonoLSB:
                image = image.convertToFormat(QImage.Format_Mono)
            fmt = QImage.Format_Mono
        else:
            if (fmt != QImage.Format_RGB32 and fmt != QImage.Format_ARGB32):
                image = image.convertToFormat(QImage.Format_ARGB32)
                fmt = QImage.Format_ARGB32

        w = image.width()
        h = image.height()
        d = image.depth()

        if fmt == QImage.Format_Mono:
            bytes_per_line = (w + 7) >> 3
            data = image.constBits().asstring(bytes_per_line * h)
            return self.write_image(data, w, h, d, cache_key=cache_key)

        has_alpha = False
        soft_mask = None

        if fmt == QImage.Format_ARGB32:
            tmask = image.constBits().asstring(4*w*h)[self.alpha_bit::4]
            sdata = bytearray(tmask)
            vals = set(sdata)
            vals.discard(255)  # discard opaque pixels
            has_alpha = bool(vals)
            if has_alpha:
                # Blend image onto a white background as otherwise Qt will render
                # transparent pixels as black
                background = QImage(image.size(), QImage.Format_ARGB32_Premultiplied)
                background.fill(Qt.white)
                painter = QPainter(background)
                painter.drawImage(0, 0, image)
                painter.end()
                image = background

        ba = QByteArray()
        buf = QBuffer(ba)
        image.save(buf, 'jpeg', 94)
        data = bytes(ba.data())

        if has_alpha:
            soft_mask = self.write_image(tmask, w, h, 8)

        return self.write_image(data, w, h, 32, dct=True,
                                soft_mask=soft_mask, cache_key=cache_key)
Beispiel #30
0
 def __call__(self, canvas):
     if canvas.has_selection and canvas.selection_state.rect is not None:
         pimg = self.after_image
         img = self.after_image = QImage(canvas.current_image)
         rect = QRectF(*get_selection_rect(img, canvas.selection_state.rect, canvas.target))
         p = QPainter(img)
         p.setRenderHint(p.SmoothPixmapTransform, True)
         p.drawImage(rect, pimg, QRectF(pimg.rect()))
         p.end()
     return self.after_image
Beispiel #31
0
 def __call__(self, canvas):
     if canvas.has_selection and canvas.selection_state.rect is not None:
         pimg = self.after_image
         img = self.after_image = QImage(canvas.current_image)
         rect = QRectF(*get_selection_rect(img, canvas.selection_state.rect, canvas.target))
         p = QPainter(img)
         p.setRenderHint(p.SmoothPixmapTransform, True)
         p.drawImage(rect, pimg, QRectF(pimg.rect()))
         p.end()
     return self.after_image
Beispiel #32
0
    def paintEvent(self, event):
        w = self.viewport().rect().width()
        painter = QPainter(self.viewport())
        painter.setClipRect(event.rect())
        floor = event.rect().bottom()
        ceiling = event.rect().top()
        fv = self.firstVisibleBlock().blockNumber()
        origin = self.contentOffset()
        doc = self.document()
        lines = []

        for num, text in self.headers:
            top, bot = num, num + 3
            if bot < fv:
                continue
            y_top = self.blockBoundingGeometry(doc.findBlockByNumber(top)).translated(origin).y()
            y_bot = self.blockBoundingGeometry(doc.findBlockByNumber(bot)).translated(origin).y()
            if max(y_top, y_bot) < ceiling:
                continue
            if min(y_top, y_bot) > floor:
                break
            painter.setFont(self.heading_font)
            br = painter.drawText(3, y_top, w, y_bot - y_top - 5, Qt.TextSingleLine, text)
            painter.setPen(QPen(self.palette().text(), 2))
            painter.drawLine(0, br.bottom()+3, w, br.bottom()+3)

        for top, bot, kind in self.changes:
            if bot < fv:
                continue
            y_top = self.blockBoundingGeometry(doc.findBlockByNumber(top)).translated(origin).y()
            y_bot = self.blockBoundingGeometry(doc.findBlockByNumber(bot)).translated(origin).y()
            if max(y_top, y_bot) < ceiling:
                continue
            if min(y_top, y_bot) > floor:
                break
            if y_top != y_bot:
                painter.fillRect(0,  y_top, w, y_bot - y_top, self.diff_backgrounds[kind])
            lines.append((y_top, y_bot, kind))
            if top in self.images:
                img, maxw = self.images[top][:2]
                if bot > top + 1 and not img.isNull():
                    y_top = self.blockBoundingGeometry(doc.findBlockByNumber(top+1)).translated(origin).y() + 3
                    y_bot -= 3
                    scaled, imgw, imgh = fit_image(img.width(), img.height(), w - 3, y_bot - y_top)
                    painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
                    painter.drawPixmap(QRect(3, y_top, imgw, imgh), img)

        painter.end()
        PlainTextEdit.paintEvent(self, event)
        painter = QPainter(self.viewport())
        painter.setClipRect(event.rect())
        for top, bottom, kind in sorted(lines, key=lambda (t, b, k):{'replace':0}.get(k, 1)):
            painter.setPen(QPen(self.diff_foregrounds[kind], 1))
            painter.drawLine(0, top, w, top)
            painter.drawLine(0, bottom - 1, w, bottom - 1)
Beispiel #33
0
 def makeQPixmap(self, width, height):
     data = numpy.zeros((width, height), float)
     data[...] = (numpy.arange(width) / (width - 1.))[:, numpy.newaxis]
     # make brush image -- diag background, with colormap on top
     img = QPixmap(width, height)
     painter = QPainter(img)
     painter.fillRect(0, 0, width, height, QBrush(QColor("white")))
     painter.fillRect(0, 0, width, height, QBrush(Qt.BDiagPattern))
     painter.drawImage(0, 0, self.colorize(data))
     painter.end()
     return img
Beispiel #34
0
 def makeQPixmap(self, width, height):
     data = numpy.zeros((width, height), float)
     data[...] = (numpy.arange(width) / (width - 1.))[:, numpy.newaxis]
     # make brush image -- diag background, with colormap on top
     img = QPixmap(width, height)
     painter = QPainter(img)
     painter.fillRect(0, 0, width, height, QBrush(QColor("white")))
     painter.fillRect(0, 0, width, height, QBrush(Qt.BDiagPattern))
     painter.drawImage(0, 0, self.colorize(data))
     painter.end()
     return img
Beispiel #35
0
 def paintEvent(self, ev):
     p = QPainter(self)
     p.setClipRect(ev.rect())
     bg = self.palette().color(QPalette.AlternateBase)
     if self.hovering:
         bg = bg.lighter(115)
     p.fillRect(self.rect(), bg)
     try:
         p.drawText(self.rect(), Qt.AlignLeft|Qt.AlignVCenter|Qt.TextSingleLine, self.rendered_text)
     finally:
         p.end()
Beispiel #36
0
def run(dev, func):
    p = QPainter(dev)
    if isinstance(dev, PdfDevice):
        dev.init_page()
    xmax, ymax = p.viewport().width(), p.viewport().height()
    try:
        func(p, xmax, ymax)
    finally:
        p.end()
    if isinstance(dev, PdfDevice):
        if dev.engine.errors_occurred:
            raise SystemExit(1)
Beispiel #37
0
def run(dev, func):
    p = QPainter(dev)
    if isinstance(dev, PdfDevice):
        dev.init_page()
    xmax, ymax = p.viewport().width(), p.viewport().height()
    try:
        func(p, xmax, ymax)
    finally:
        p.end()
    if isinstance(dev, PdfDevice):
        if dev.engine.errors_occurred:
            raise SystemExit(1)
Beispiel #38
0
        def paintEvent(self, event):
            contents_y = self.edit.verticalScrollBar().value()
            page_bottom = contents_y + self.edit.viewport().height()
            font_metrics = self.fontMetrics()
            current_block = self.edit.document().findBlock(
                self.edit.textCursor().position())

            painter = QPainter(self)

            line_count = 0
            # Iterate over all text blocks in the document.
            block = self.edit.document().begin()
            while block.isValid():
                line_count += 1

                # The top left position of the block in the document
                position = self.edit.document().documentLayout(
                ).blockBoundingRect(block).topLeft()

                # Check if the position of the block is out side of the visible
                # area.
                if position.y() > page_bottom:
                    break

                # We want the line number for the selected line to be bold.
                bold = False

                if block == current_block:
                    bold = True
                    font = painter.font()
                    font.setBold(True)
                    painter.setFont(font)

                # Draw the line number right justified at the y position of the
                # line. 3 is a magic padding number. drawText(x, y, text).
                painter.drawText(
                    self.width() - font_metrics.width(str(line_count)) - 3,
                    round(position.y()) - contents_y + font_metrics.ascent(),
                    str(line_count))

                # Remove the bold style if it was set previously.
                if bold:
                    font = painter.font()
                    font.setBold(False)
                    painter.setFont(font)

                block = block.next()

            self.highest_line = line_count
            painter.end()

            QWidget.paintEvent(self, event)
Beispiel #39
0
 def paintEvent(self, ev):
     br = ev.region().boundingRect()
     QWidget.paintEvent(self, ev)
     p = QPainter(self)
     p.setClipRect(br)
     f = p.font()
     f.setBold(True)
     f.setPointSize(20)
     p.setFont(f)
     p.setPen(Qt.SolidLine)
     r = QRect(0, self.dummy.geometry().top() + 10, self.geometry().width(), 150)
     p.drawText(r, Qt.AlignHCenter | Qt.AlignTop | Qt.TextSingleLine, self.text)
     p.end()
Beispiel #40
0
 def paintEvent(self, ev):
     br = ev.region().boundingRect()
     QWidget.paintEvent(self, ev)
     p = QPainter(self)
     p.setClipRect(br)
     f = p.font()
     f.setBold(True)
     f.setPointSize(20)
     p.setFont(f)
     p.setPen(Qt.SolidLine)
     r = QRect(0, self.dummy.geometry().top() + 10, self.geometry().width(), 150)
     p.drawText(r, Qt.AlignHCenter | Qt.AlignTop | Qt.TextSingleLine, self.text)
     p.end()
Beispiel #41
0
 def insert_cover(self):
     if self.cover_data is None:
         return
     item_path = os.path.join(self.tmp_path, 'cover.pdf')
     printer = get_pdf_printer(self.opts, output_file_name=item_path)
     self.combine_queue.insert(0, item_path)
     p = QPixmap()
     p.loadFromData(self.cover_data)
     if not p.isNull():
         painter = QPainter(printer)
         draw_image_page(printer, painter, p,
                 preserve_aspect_ratio=self.opts.preserve_cover_aspect_ratio)
         painter.end()
     printer.abort()
Beispiel #42
0
 def insert_cover(self):
     if not isinstance(self.cover_data, bytes):
         return
     item_path = os.path.join(self.tmp_path, "cover.pdf")
     printer = get_pdf_printer(self.opts, output_file_name=item_path, for_comic=True)
     self.combine_queue.insert(0, item_path)
     p = QPixmap()
     p.loadFromData(self.cover_data)
     if not p.isNull():
         painter = QPainter(printer)
         draw_image_page(printer, painter, p, preserve_aspect_ratio=self.opts.preserve_cover_aspect_ratio)
         painter.end()
         self.append_doc(item_path)
     printer.abort()
Beispiel #43
0
def create_icon(text, palette=None, sz=32, divider=2):
    if palette is None:
        palette = QApplication.palette()
    img = QImage(sz, sz, QImage.Format_ARGB32)
    img.fill(Qt.transparent)
    p = QPainter(img)
    p.setRenderHints(p.TextAntialiasing | p.Antialiasing)
    qDrawShadeRect(p, img.rect(), palette, fill=QColor('#ffffff'), lineWidth=1, midLineWidth=1)
    f = p.font()
    f.setFamily('Liberation Sans'), f.setPixelSize(sz // divider), f.setBold(True)
    p.setFont(f), p.setPen(Qt.black)
    p.drawText(img.rect().adjusted(2, 2, -2, -2), Qt.AlignCenter, text)
    p.end()
    return QIcon(QPixmap.fromImage(img))
Beispiel #44
0
        def numberbarPaint(self, number_bar, event):
            """
			Pain the line numbers
			"""

            font_metrics = self.fontMetrics()
            current_line = self.document().findBlock(
                self.textCursor().position()).blockNumber() + 1

            block = self.firstVisibleBlock()
            line_count = block.blockNumber()
            painter = QPainter(number_bar)

            fg_pen = QtGui.QPen(QtGui.QColor("gray"))

            painter.setFont(self.font)
            painter.setPen(fg_pen)
            painter.fillRect(event.rect(), self.palette().base())

            # Iterate over all visible text blocks in the document.
            while block.isValid():
                line_count += 1
                block_top = self.blockBoundingGeometry(block).translated(
                    self.contentOffset()).top()

                # Check if the position of the block is out side of the visible
                # area.
                if not block.isVisible() or block_top >= event.rect().bottom():
                    break

                # We want the line number for the selected line to be bold.
                if line_count == current_line:
                    font = painter.font()
                    font.setBold(True)
                    painter.setFont(font)
                else:
                    font = painter.font()
                    font.setBold(False)
                    painter.setFont(font)

                # Draw the line number right justified at the position of the line.
                paint_rect = QRect(0, block_top, number_bar.width(),
                                   font_metrics.height())
                painter.drawText(paint_rect, Qt.AlignRight,
                                 unicode("x%.4d" % line_count))

                block = block.next()

            painter.end()
Beispiel #45
0
    def paintEvent(self, event):
        contents_y = self.edit.verticalScrollBar().value()
        page_bottom = contents_y + self.edit.viewport().height()
        font_metrics = self.fontMetrics()
        current_block = self.edit.document().findBlock(self.edit.textCursor().position())

        painter = QPainter(self)

        line_count = 0
        # Iterate over all text blocks in the document.
        block = self.edit.document().begin()
        while block.isValid():
            line_count += 1

            # The top left position of the block in the document
            position = self.edit.document().documentLayout().blockBoundingRect(block).topLeft()

            # Check if the position of the block is out side of the visible
            # area.
            if position.y() > page_bottom:
                break

            # We want the line number for the selected line to be bold.
            bold = False
            if block == current_block:
                bold = True
                font = painter.font()
                font.setBold(True)
                painter.setFont(font)

            # Draw the line number right justified at the y position of the
            # line. 3 is a magic padding number. drawText(x, y, text).
            painter.drawText(self.width() - font_metrics.width(str(line_count)) - 3, 
                round(position.y()) - contents_y + font_metrics.ascent()+3, 
                str(line_count))

            # Remove the bold style if it was set previously.
            if bold:
                font = painter.font()
                font.setBold(False)
                painter.setFont(font)

            block = block.next()

        self.highest_line = line_count
        painter.end()

        QWidget.paintEvent(self, event)
Beispiel #46
0
 def paintEvent(self, event):
     QWidget.paintEvent(self, event)
     p = QPainter(self)
     p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
     try:
         self.draw_background(p)
         if self.original_image_data is None:
             return
         if not self.is_valid:
             return self.draw_image_error(p)
         self.load_pixmap()
         self.draw_pixmap(p)
         if self.selection_state.rect is not None:
             self.draw_selection_rect(p)
     finally:
         p.end()
Beispiel #47
0
 def paintEvent(self, event):
     QWidget.paintEvent(self, event)
     p = QPainter(self)
     p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
     try:
         self.draw_background(p)
         if self.original_image_data is None:
             return
         if not self.is_valid:
             return self.draw_image_error(p)
         self.load_pixmap()
         self.draw_pixmap(p)
         if self.selection_state.rect is not None:
             self.draw_selection_rect(p)
     finally:
         p.end()
Beispiel #48
0
 def paintEvent(self, event):
     canvas_size = self.rect()
     width = self.current_pixmap_size.width()
     extrax = canvas_size.width() - width
     if extrax < 0: extrax = 0
     x = int(extrax/2.)
     height = self.current_pixmap_size.height()
     extray = canvas_size.height() - height
     if extray < 0: extray = 0
     y = int(extray/2.)
     target = QRect(x, y, width, height)
     p = QPainter(self)
     p.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
     p.drawPixmap(target, self.pixmap.scaled(target.size(),
         Qt.KeepAspectRatio, Qt.SmoothTransformation))
     p.end()
Beispiel #49
0
    def paintEvent(self, event):
        h = self.size().height()
        w = self.size().width()

        contents_y = self.edit.verticalScrollBar().value()
        page_bottom = contents_y + self.edit.viewport().height()
        font_metrics = self.fontMetrics()

        painter = QPainter(self)
        painter.setBackgroundMode(QtCore.Qt.OpaqueMode)
        bgc = QtGui.QColor(0, 0, 0)
        painter.fillRect(0, 0, w, h, bgc)

        numbersborderc = QtGui.QColor(55, 75, 75)
        painter.setPen(numbersborderc)
        painter.drawLine(w - 1, 0, w - 1, h)

        bg = QtGui.QBrush(bgc)
        painter.setBackground(bg)
        textc = QtGui.QColor(55, 255, 255)
        painter.setPen(textc)
        fg = QtGui.QBrush(bgc)
        painter.setBrush(fg)

        line_count = 0
        # Iterate over all text blocks in the document.
        block = self.edit.document().begin()
        while block.isValid():
            line_count += 1

            # The top left position of the block in the document
            position = self.edit.document().documentLayout().blockBoundingRect(
                block).topLeft()

            # Draw the line number right justified at the y position of the
            # line. 3 is a magic padding number. drawText(x, y, text).
            painter.drawText(
                self.width() - font_metrics.width(str(line_count)) - 8,
                round(position.y()) - contents_y + font_metrics.ascent(),
                str(line_count))

            block = block.next()

        self.highest_line = line_count
        painter.end()

        QWidget.paintEvent(self, event)
Beispiel #50
0
 def insert_cover(self):
     if self.cover_data is None:
         return
     item_path = os.path.join(self.tmp_path, 'cover.pdf')
     printer = get_pdf_printer(self.opts, output_file_name=item_path)
     self.combine_queue.insert(0, item_path)
     p = QPixmap()
     p.loadFromData(self.cover_data)
     if not p.isNull():
         painter = QPainter(printer)
         draw_image_page(
             printer,
             painter,
             p,
             preserve_aspect_ratio=self.opts.preserve_cover_aspect_ratio)
         painter.end()
     printer.abort()
Beispiel #51
0
		def numberbarPaint(self, number_bar, event):
		
			"""
			Pain the line numbers
			"""
		
			font_metrics = self.fontMetrics()
			current_line = self.document().findBlock(self.textCursor().position()).blockNumber() + 1
	 
			block = self.firstVisibleBlock()
			line_count = block.blockNumber()
			painter = QPainter(number_bar)
			
			fg_pen = QtGui.QPen(QtGui.QColor("gray"))
			
			painter.setFont(self.font)
			painter.setPen(fg_pen)
			painter.fillRect(event.rect(), self.palette().base())
	 
			# Iterate over all visible text blocks in the document.
			while block.isValid():
				line_count += 1
				block_top = self.blockBoundingGeometry(block).translated(self.contentOffset()).top()
		 
				# Check if the position of the block is out side of the visible
				# area.
				if not block.isVisible() or block_top >= event.rect().bottom():
					break
		 
				# We want the line number for the selected line to be bold.
				if line_count == current_line:
					font = painter.font()
					font.setBold(True)
					painter.setFont(font)
				else:
					font = painter.font()
					font.setBold(False)
					painter.setFont(font)
		 
				# Draw the line number right justified at the position of the line.
				paint_rect = QRect(0, block_top, number_bar.width(), font_metrics.height())
				painter.drawText(paint_rect, Qt.AlignRight, unicode("x%.4d" % line_count))
		 
				block = block.next()
	 
			painter.end()
Beispiel #52
0
    def render_images(self, outpath, mi, items):
        printer = get_pdf_printer(self.opts, for_comic=True, output_file_name=outpath)
        printer.setDocName(mi.title)

        painter = QPainter(printer)
        painter.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)

        for i, imgpath in enumerate(items):
            self.log("Rendering image:", i)
            p = QPixmap()
            p.load(imgpath)
            if not p.isNull():
                if i > 0:
                    printer.newPage()
                draw_image_page(printer, painter, p)
            else:
                self.log.warn("Failed to load image", i)
        painter.end()
Beispiel #53
0
    def paintEvent(self, ev):
        p = QPainter(self)
        p.setClipRect(ev.rect())
        palette = self.palette()
        p.setPen(palette.color(QPalette.WindowText))
        if not self.is_first:
            p.drawLine(0, 0, self.width(), 0)
        try:
            for row in self.rows:
                for cell in row:
                    p.save()
                    try:
                        cell.draw(p, self.width(), palette)
                    finally:
                        p.restore()

        finally:
            p.end()
Beispiel #54
0
    def do_print(self, printer):
        painter = QPainter(printer)
        zoomx = printer.logicalDpiX() / self.view.logicalDpiX()
        zoomy = printer.logicalDpiY() / self.view.logicalDpiY()
        painter.scale(zoomx, zoomy)
        pr = printer.pageRect()
        self.view.page().setViewportSize(
            QSize(pr.width() / zoomx,
                  pr.height() / zoomy))
        evaljs = self.mf.evaluateJavaScript
        loop = QEventLoop(self)
        first = True

        for path in self.iterator.spine:
            self.loaded_ok = None
            load_html(path,
                      self.view,
                      codec=getattr(path, 'encoding', 'utf-8'),
                      mime_type=getattr(path, 'mime_type', None))
            while self.loaded_ok is None:
                loop.processEvents(loop.ExcludeUserInputEvents)
            if not self.loaded_ok:
                return error_dialog(self.parent(),
                                    _('Failed to render'),
                                    _('Failed to render document %s') % path,
                                    show=True)
            evaljs(self.paged_js)
            evaljs('''
                document.body.style.backgroundColor = "white";
                paged_display.set_geometry(1, 0, 0, 0);
                paged_display.layout();
                paged_display.fit_images();
            ''')

            while True:
                if not first:
                    printer.newPage()
                first = False
                self.mf.render(painter)
                nsl = evaljs('paged_display.next_screen_location()').toInt()
                if not nsl[1] or nsl[0] <= 0: break
                evaljs('window.scrollTo(%d, 0)' % nsl[0])

        painter.end()
Beispiel #55
0
 def paintEvent(self, event):
     canvas_size = self.rect()
     width = self.current_pixmap_size.width()
     extrax = canvas_size.width() - width
     if extrax < 0: extrax = 0
     x = int(extrax / 2.)
     height = self.current_pixmap_size.height()
     extray = canvas_size.height() - height
     if extray < 0: extray = 0
     y = int(extray / 2.)
     target = QRect(x, y, width, height)
     p = QPainter(self)
     p.setRenderHints(QPainter.Antialiasing
                      | QPainter.SmoothPixmapTransform)
     p.drawPixmap(
         target,
         self.pixmap.scaled(target.size(), Qt.KeepAspectRatio,
                            Qt.SmoothTransformation))
     p.end()
Beispiel #56
0
 def failed_img(self):
     if self._failed_img is None:
         i = QImage(200, 150, QImage.Format_ARGB32)
         i.fill(Qt.white)
         p = QPainter(i)
         r = i.rect().adjusted(10, 10, -10, -10)
         n = QPen(Qt.DashLine)
         n.setColor(Qt.black)
         p.setPen(n)
         p.drawRect(r)
         p.setPen(Qt.black)
         f = self.font()
         f.setPixelSize(20)
         p.setFont(f)
         p.drawText(r.adjusted(10, 0, -10, 0),
                    Qt.AlignCenter | Qt.TextWordWrap,
                    _('Image could not be rendered'))
         p.end()
         self._failed_img = QPixmap.fromImage(i)
     return self._failed_img
Beispiel #57
0
def create_icon(text, palette=None, sz=32, divider=2):
    if palette is None:
        palette = QApplication.palette()
    img = QImage(sz, sz, QImage.Format_ARGB32)
    img.fill(Qt.transparent)
    p = QPainter(img)
    p.setRenderHints(p.TextAntialiasing | p.Antialiasing)
    qDrawShadeRect(p,
                   img.rect(),
                   palette,
                   fill=QColor('#ffffff'),
                   lineWidth=1,
                   midLineWidth=1)
    f = p.font()
    f.setFamily('Liberation Sans'), f.setPixelSize(sz //
                                                   divider), f.setBold(True)
    p.setFont(f), p.setPen(Qt.black)
    p.drawText(img.rect().adjusted(2, 2, -2, -2), Qt.AlignCenter, text)
    p.end()
    return QIcon(QPixmap.fromImage(img))