Ejemplo n.º 1
0
    def svg(self, filename, rect=None, resolution=72.0, paperColor=None):
        """Create a SVG file for the selected rect or the whole page.

        The filename may be a string or a QIODevice object. The rectangle is
        relative to our top-left position. Normally vector graphics are
        rendered, but in cases where that is not possible, the resolution will
        be used to determine the DPI for the generated rendering.

        """
        # map to the original page
        source = self.pageRect() if rect is None else self.mapFromPage().rect(
            rect)
        # scale to target size
        w = source.width() * self.scaleX
        h = source.height() * self.scaleY
        if self.computedRotation & 1:
            w, h = h, w
        targetSize = QSizeF(w, h) * resolution / self.dpi

        svg = QSvgGenerator()
        if isinstance(filename, str):
            svg.setFileName(filename)
        else:
            svg.setOutputDevice(filename)
        svg.setResolution(int(resolution))
        svg.setSize(targetSize.toSize())
        svg.setViewBox(QRectF(0, 0, targetSize.width(), targetSize.height()))
        return self.output(svg, source, paperColor)
Ejemplo n.º 2
0
def grab_svg(scene):
    """
    Return a SVG rendering of the scene contents.

    Parameters
    ----------
    scene : :class:`CanvasScene`

    """
    from PyQt5.QtSvg import QSvgGenerator
    svg_buffer = QBuffer()
    gen = QSvgGenerator()
    gen.setOutputDevice(svg_buffer)

    items_rect = scene.itemsBoundingRect().adjusted(-10, -10, 10, 10)

    if items_rect.isNull():
        items_rect = QRectF(0, 0, 10, 10)

    width, height = items_rect.width(), items_rect.height()
    rect_ratio = float(width) / height

    # Keep a fixed aspect ratio.
    aspect_ratio = 1.618
    if rect_ratio > aspect_ratio:
        height = int(height * rect_ratio / aspect_ratio)
    else:
        width = int(width * aspect_ratio / rect_ratio)

    target_rect = QRectF(0, 0, width, height)
    source_rect = QRectF(0, 0, width, height)
    source_rect.moveCenter(items_rect.center())

    gen.setSize(target_rect.size().toSize())
    gen.setViewBox(target_rect)

    painter = QPainter(gen)

    # Draw background.
    painter.setBrush(QBrush(Qt.white))
    painter.drawRect(target_rect)

    # Render the scene
    scene.render(painter, target_rect, source_rect)
    painter.end()

    buffer_str = bytes(svg_buffer.buffer())
    return buffer_str.decode("utf-8")