Example #1
0
    def printPreview(self, obj, data):
        from PyQt5.QtPrintSupport import QPrinter, QPrintPreviewDialog
        from PyQt5.QtGui import QTextDocument, QTextCursor, QTextTableFormat, QTextFrameFormat  #, QFont
        import time

        self.printer = QPrinter()
        self.printer.setPageSize(QPrinter.A4)
        self.printer.setOrientation(QPrinter.Landscape)
        self.printer.setFullPage(True)
        self.printer.setPageMargins(2, 2, 2, 2, QPrinter.Millimeter)
        #self.printer.setFont(QFont("times",22))

        dialog = QPrintPreviewDialog(self.printer)
        #dialog.showFullScreen()

        document = QTextDocument()

        #document.setHtml("<html><head></head><body></body></html>")
        document.setHtml("")
        cursor = QTextCursor(document)

        # Titolo
        cursor.insertHtml("<h2 align=center>%s</h2>" % obj['title'])
        cursor.insertText("\n")
        # Data
        cursor.insertHtml("<h5 align=left>%s</h5>" % time.strftime("%d/%m/%Y"))
        cursor.insertText("\n")

        # Table
        tableFormat = QTextTableFormat()
        tableFormat.setCellPadding(2)
        tableFormat.setCellSpacing(3)
        #tableFormat.setBorderStyle(QTextFrameFormat.BorderStyle_Ridge)
        tableFormat.setBorder(0)

        cursor.insertTable(len(data) + 2, len(obj['col_name']), tableFormat)

        # Intestazioni
        for table_title in obj['col_name']:
            cursor.insertHtml('<font size="4" color="blue"><b>%s</b></font>' %
                              table_title)
            cursor.movePosition(QTextCursor.NextCell)

        # Riga bianca
        for table_title in obj['col_name']:
            cursor.insertText(' ')
            cursor.movePosition(QTextCursor.NextCell)

        # Dati Tabella
        for r in data:
            for k in obj['col_order']:
                v = r[k]
                if v is not None:
                    #cursor.insertText(str(v))
                    cursor.insertHtml('<font size="4">%s</font>' % v)
                    cursor.movePosition(QTextCursor.NextCell)

        dialog.paintRequested.connect(document.print_)
        dialog.setFixedSize(1500, 1050)
        dialog.exec_()
Example #2
0
    def _get_textdoc(self, index):
        """Create the QTextDocument of an item.

        Args:
            index: The QModelIndex of the item to draw.
        """
        # FIXME we probably should do eliding here. See
        # qcommonstyle.cpp:viewItemDrawText
        text_option = QTextOption()
        if self._opt.features & QStyleOptionViewItem.WrapText:
            text_option.setWrapMode(QTextOption.WordWrap)
        else:
            text_option.setWrapMode(QTextOption.ManualWrap)
        text_option.setTextDirection(self._opt.direction)
        text_option.setAlignment(QStyle.visualAlignment(
            self._opt.direction, self._opt.displayAlignment))

        self._doc = QTextDocument(self)
        if index.parent().isValid():
            self._doc.setPlainText(self._opt.text)
        else:
            self._doc.setHtml('<b>{}</b>'.format(html.escape(self._opt.text)))
        self._doc.setDefaultFont(self._opt.font)
        self._doc.setDefaultTextOption(text_option)
        self._doc.setDefaultStyleSheet(style.get_stylesheet("""
            .highlight {
                {{ color['completion.match.fg'] }}
            }
        """))
        self._doc.setDocumentMargin(2)

        if index.column() == 0:
            marks = index.data(basecompletion.Role.marks)
            if marks is None:
                return
            for mark in marks:
                cur = QTextCursor(self._doc)
                cur.setPosition(mark[0])
                cur.setPosition(mark[1], QTextCursor.KeepAnchor)
                txt = cur.selectedText()
                cur.removeSelectedText()
                cur.insertHtml('<span class="highlight">{}</span>'.format(
                    html.escape(txt)))
    def CreatePDF(self, out, timestamp, data, frame, rows, columns, fileName,
                  VManager):
        ''' Create PDF QgsTask '''
        QCoreApplication.processEvents()
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        font_normal = QFont("Helvetica", 10, QFont.Normal)
        font_bold = QFont("Helvetica", 12, QFont.Bold)

        printer = QPrinter(QPrinter.HighResolution)
        printer.setOrientation(QPrinter.Portrait)
        printer.setOutputFormat(QPrinter.PdfFormat)
        printer.setFullPage(True)
        printer.setPaperSize(QPrinter.A4)
        printer.setOutputFileName(out)
        printer.setPageMargins(15, 15, 15, 15, QPrinter.Point)
        printer.setColorMode(QPrinter.Color)

        document = QTextDocument()
        document.setDefaultFont(font_normal)

        cursor = QTextCursor(document)
        cursor.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor)
        cursor.insertHtml("""
            <p style='text-align: center;'>
            <img style='display: block; margin-left: auto; margin-right: auto;' 
            src=\':/imgFMV/images/header_logo.png\' width='200' height='25' />
            </p>
            <p style='text-align: center;'>
            <strong>Video :&nbsp;</strong>%s<strong>
            </p>
            <p style='text-align: center;'>
            <strong>TimeStamp :&nbsp;</strong>%s</p><br><br>
            """ % (fileName, timestamp))

        tableFormat = QTextTableFormat()
        tableFormat.setHeaderRowCount(1)
        tableFormat.setBorderBrush(QBrush(Qt.black))
        tableFormat.setAlignment(Qt.AlignHCenter)
        tableFormat.setCellPadding(2)
        tableFormat.setCellSpacing(2)

        centerFormat = QTextBlockFormat()
        centerFormat.setAlignment(Qt.AlignCenter)
        cursor.insertBlock(centerFormat)

        textTable = cursor.insertTable(rows + 1, columns, tableFormat)

        tableHeaderFormat = QTextCharFormat()
        tableHeaderFormat.setFont(font_bold)
        tableHeaderFormat.setBackground(QColor("#67b03a"))
        tableHeaderFormat.setForeground(Qt.white)

        alternate_background = QTextCharFormat()
        alternate_background.setBackground(QColor("#DDE9ED"))

        for column in range(columns):
            cell = textTable.cellAt(0, column)
            cell.setFormat(tableHeaderFormat)
            cellCursor = cell.firstCursorPosition()
            cellCursor.insertText(VManager.horizontalHeaderItem(column).text())

        row = 0
        for key in sorted(data.keys()):
            cell0 = textTable.cellAt(row + 1, 0)
            cell1 = textTable.cellAt(row + 1, 1)
            cell2 = textTable.cellAt(row + 1, 2)
            if (row + 1) % 2 == 0:
                cell0.setFormat(alternate_background)
                cell1.setFormat(alternate_background)
                cell2.setFormat(alternate_background)
            cellCursor0 = cell0.firstCursorPosition()
            cellCursor0.insertText(str(key))
            cellCursor1 = cell1.firstCursorPosition()
            cellCursor1.insertText(str(data[key][0]))
            cellCursor2 = cell2.firstCursorPosition()
            cellCursor2.insertText(str(data[key][1]))
            row += 1

        cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor)

        cursor.insertHtml("""
        <br><p style='text-align: center;'><strong>Current Frame</strong></p><br>
        """)

        centerFormat = QTextBlockFormat()
        centerFormat.setAlignment(Qt.AlignHCenter)
        cursor.insertBlock(centerFormat)
        cursor.insertImage(frame.scaledToWidth(500))
        QCoreApplication.processEvents()
        document.print_(printer)
        QCoreApplication.processEvents()
Example #4
0
    def SaveAsPDF(self):
        """ Save Table as pdf """
        fileName, _ = QFileDialog.getSaveFileName(self, "Save File", "",
                                                  "PDF Files (*.pdf)")
        if fileName == "":
            return

        try:
            videoName = self.player.fileName
            timestamp = self.player.player.position()
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            rows = self.VManager.rowCount()
            columns = self.VManager.columnCount()

            printer = QPrinter(QPrinter.HighResolution)
            innerRect = printer.pageRect()
            sizeF = QSizeF(innerRect.size().width(), innerRect.size().height())
            header = QTextDocument()
            header.setPageSize(sizeF)
            cursor_header = QTextCursor(header)
            format1 = QTextCharFormat()
            format1.setFontPointSize(16)
            cursor_header.insertHtml(
                "<p style='text-align: left;'><strong>Video</strong>: %s <strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;TimeStamp</strong>: %s </p>"
                % (videoName, timestamp))
            cursor_header.insertHtml("<br><br><br> ")

            cursor_header.select(QTextCursor.Document)
            fragment_header = cursor_header.selection()

            document = QTextDocument()
            cursor = QTextCursor(document)
            tableFormat = QTextTableFormat()
            tableFormat.setHeaderRowCount(1)
            tableFormat.setBorderBrush(QBrush(Qt.black))
            tableFormat.setAlignment(Qt.AlignHCenter)
            tableFormat.setCellPadding(5)
            tableFormat.setCellSpacing(5)

            cursor.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor)
            cursor.insertFragment(fragment_header)

            textTable = cursor.insertTable(rows + 1, columns, tableFormat)

            tableHeaderFormat = QTextCharFormat()
            tableHeaderFormat.setBackground(QColor("#DADADA"))

            for column in range(columns):
                cell = textTable.cellAt(0, column)
                cell.setFormat(tableHeaderFormat)
                cellCursor = cell.firstCursorPosition()
                cellCursor.insertText(
                    self.VManager.horizontalHeaderItem(column).data(
                        Qt.DisplayRole))

            for row in range(rows):
                for column in range(columns):
                    item = self.VManager.item(row, column)
                    if item is not None:
                        cell = textTable.cellAt(row + 1, column)
                        cellCursor = cell.firstCursorPosition()
                        cellCursor.insertText(
                            self.VManager.item(row, column).text())

            cursor.movePosition(QTextCursor.End)
            printer.setOrientation(QPrinter.Portrait)

            printer.setPageMargins(30, 100, 10, 40, QPrinter.DevicePixel)
            printer.setFullPage(True)
            printer.setPageSize(QPrinter.A4)
            printer.setOutputFormat(QPrinter.PdfFormat)
            printer.setOutputFileName(fileName)

            document.print_(printer)
            QApplication.restoreOverrideCursor()
            qgsu.showUserAndLogMessage(
                QCoreApplication.translate("QgsFmvMetadata",
                                           "Succesfully creating PDF"))
        except Exception as e:
            QApplication.restoreOverrideCursor()
            qgsu.showUserAndLogMessage(QCoreApplication.translate(
                "QgsFmvMetadata", "Failed creating PDF"),
                                       level=QGis.Warning)
            return
        return