Exemple #1
0
    def save_report(self, filename="", extension=".HTML"):
        """
        Save the generated report to the specified file
        Currently only html
        """
        full_filename = filename + extension.lower()
        full_filename = os.path.join(
            self._project_control.get_project_dir_absolute_path(),
            full_filename)

        if not self.report_html:
            self.__log.info("No report to save")
            return

        if extension == '.HTML':
            # HTML can contain non-ascii, so need to open with right encoding
            with open(full_filename, 'w', encoding='utf-8') as report_file:
                report_file.write(self.report_html)
                self.__log.info("Report written")
        elif extension == '.PDF':
            document = QTextDocument(parent=None)
            document.setHtml(self.report_html)
            printer = QPdfWriter(full_filename)
            printer.setPageSize(printer.A3)  # A3 to fit A4 page
            document.print_(printer)
        else:
            raise NotImplementedError

        # Show the generated report in the default browser
        url = os.path.realpath(full_filename)
        open_url(url=url)
    def saveOutputPDF(self):
        filesTypes = "Plik tekstowy (*.txt);;Plik PDF (*.pdf)"
        name, filter = QFileDialog.getSaveFileName(self.mainWindow,
                                                   'Zapisz plik', "Bez nazwy",
                                                   filesTypes)
        if not name:
            return
        if filter == "Plik PDF (*.pdf)":
            try:
                linesOriginalText = self.mainWindow.ui.plainTextEditOutputPDF.toPlainText(
                ).split("\n")
                template = pd.DataFrame(linesOriginalText,
                                        dtype=str,
                                        columns=[""])
                html = template.to_html(index=False, border=0)
                htmlFile = open("temp.html", "w", encoding="utf-8")
                htmlFile.write(html)
                htmlFile.close()

                doc = QTextDocument()
                try:
                    html = open("temp.html", "r", encoding="utf-8")
                except Exception as inst:
                    UiFunction.showErrorDialog(
                        "Wystąpił problem z szablonem PDF \n" + str(inst))
                doc.setHtml(html.read())
                html.close()

                try:
                    printer = QPrinter()
                    printer.setOutputFileName(name)
                    printer.setOutputFormat(QPrinter.PdfFormat)
                    printer.setPageSize(QPrinter.A4)
                    printer.setPageMargins(4, 4, 4, 4, QPrinter.Millimeter)

                    doc.print_(printer)
                except Exception as inst:
                    UiFunction.showErrorDialog(
                        "Wystąpił problem z generowaniem pliku PDF \n" +
                        str(inst))
                os.remove('temp.html')
            except Exception as inst:
                UiFunction.showErrorDialog(
                    "Wystąpił problem z tworzeniem pliku PDF \n" + str(inst))

        elif filter == "Plik tekstowy (*.txt)":
            try:
                try:
                    file = open(name, 'w')
                except Exception as inst:
                    UiFunction.showErrorDialog(
                        "Wystąpił problem z wybranym plikiem \n" + str(inst))
                output = self.mainWindow.ui.plainTextEditOutputPDF.toPlainText(
                )
                file.write(output)
                file.close()
            except Exception as inst:
                UiFunction.showErrorDialog(
                    "Wystąpił problem z zapisem pliku \n" + str(inst))
    def sizeHint(self, option, index):

        options = QStyleOptionViewItem(option)
        self.initStyleOption(options, index)

        doc = QTextDocument()
        doc.setHtml(options.text)
        doc.setTextWidth(options.rect.width())
        return QSize(doc.idealWidth(), doc.size().height())
    def paint(self, painter, option, index):
        """ Renders the delegate using the given painter and style option for the item specified by index. """

        # If the index is invalid we have nothing to draw
        if not index.isValid():
            return

        options = QStyleOptionViewItem(option)
        self.initStyleOption(options, index)

        painter.save()

        # sometimes a paint event occurs after a element is removed selector static selection
        # but before qt list widget gets updated. This will cause isMissing and isFilteredOut to fail.
        # early out when this happens
        if options.text not in self._selector.staticSelection:
            return
        missing = self._selector.staticSelection.isMissing(options.text)
        filteredOut = self._selector.staticSelection.isFilteredOut(
            options.text)
        doc = QTextDocument()
        html = '''{0}'''.format(options.text)
        if filteredOut:
            html = '''<i>''' + html + '''</i>'''
        if missing:
            html = '''<s>''' + html + '''</s>'''
        doc.setHtml(html)

        options.text = ""

        #if options.widget is not None:
        QApplication.style().drawControl(QStyle.CE_ItemViewItem, options,
                                         painter)

        #Shift text right to make icon visible
        iconSize = options.icon.actualSize(
            options.rect.size()) if options.icon is not None else QSize(0, 0)
        painter.translate(options.rect.left() + iconSize.width(),
                          options.rect.top())
        clip = QRect(0, 0,
                     options.rect.width() + iconSize.width(),
                     options.rect.height())

        painter.setClipRect(clip)
        ctx = QAbstractTextDocumentLayout.PaintContext()
        #set text color to red for selected item
        if missing or filteredOut:
            ctx.palette.setColor(QPalette.Text, QColor(85, 85, 85))
        ctx.clip = clip
        doc.documentLayout().draw(painter, ctx)

        painter.restore()
Exemple #5
0
    def draw(cls, x, y, self: PreparedText, painter: QPainter):
        font = QFont(self.fontName)
        if self.fontSize:
            font.setPointSizeF(self.fontSize)
        if self.fontBold:
            font.setBold(True)
        if self.fontItalic:
            font.setItalic(True)
        brushStyle = self.brushStyle or Qt.BrushStyle.SolidPattern
        w = self.width
        h = self.height
        tx = self.left + x
        ty = self.top + y
        if self.border:
            w -= self.border.width
            h -= self.border.width * 2
            tx += self.border.width
            ty += self.border.width
        rect = QRectF(tx, ty, w, h)

        if self.backColor:
            painter.setBrush(brush_style_map[brushStyle])
            painter.fillRect(rect, QColor('#' + hex(self.backColor)[2:]))
        if self.allowTags:
            doc = QTextDocument()
            doc.setDefaultFont(font)
            doc.setHtml(self.text)
            doc.setDocumentMargin(0)
            painter.save()
            painter.translate(tx + 2, ty + 1)
            doc.drawContents(painter, QRectF(0, 0, self.width, self.height))
            painter.restore()
        else:
            painter.save()
            painter.setFont(font)
            flags = cls.textFlags(self)
            rect.setX(rect.x() + 2)
            rect.setY(rect.y() + 1)
            painter.drawText(rect, flags, self.text)
            painter.restore()
        if self.border and self.border.color is not None:
            old_pen = painter.pen()
            pen = QPen(
                QColor(self.border.color), self.border.width,
                pen_style_map.get(self.border.style, Qt.PenStyle.SolidLine))
            painter.setPen(pen)
            painter.drawLines(
                cls.getLines(self, self.left + x, self.top + y,
                             self.left + self.width + x,
                             self.top + y + self.height))
            painter.setPen(old_pen)
Exemple #6
0
 def highlightCode(self, code, language):
     #converting the html to platin
     td = QTextDocument()
     td.setHtml(code)
     print("the plain text is here : " + td.toPlainText())
     codeLexer = get_lexer_by_name(language)
     f = open("highlightTest.html", 'wb')
     #fi = open("highlightTest.png",'wb')
     #style = get_style_by_name("native")
     formatter = HtmlFormatter(full=True, noclasses=True, encoding="UTF-8")
     #imgFormater = ImageFormatter()
     result = highlight(td.toPlainText(), codeLexer, formatter)
     td.setHtml(result.decode("UTF-8"))
     print(td.toHtml())
     return td.toHtml()
Exemple #7
0
 def f():
     doc = QTextDocument()
     tables = lookup(line.text())
     doc.setHtml(
         template.render(request={"script_root": ""},
                         tables=tables,
                         url_for=lambda *_, **__: None))
     doc.setTextWidth(doc.size().width())
     pixmap = QPixmap(doc.size().width(), doc.size().height())
     pixmap.fill(QColor(0, 0, 0, 0))
     painter = QPainter(pixmap)
     doc.drawContents(painter)
     painter.end()
     lab.setPixmap(pixmap)
     lab.setFixedSize(pixmap.size())
Exemple #8
0
    def print(self, printer: QPrinter) -> None:
        print_options = PrintOptions(
            print_no=self.ui.check_box_no_column.isChecked(),
            print_code=self.ui.check_box_code_column.isChecked(),
            print_description=self.ui.check_box_details_column.isChecked(),
            print_list_price=self.ui.check_box_list_price_column.isChecked(),
            print_discount=self.ui.check_box_discount_column.isChecked(),
            print_price=self.ui.check_box_price_column.isChecked(),
            print_quantity=self.ui.check_box_quantity_column.isChecked(),
            print_total=self.ui.check_box_total_column.isChecked()
        )
        margin = 5
        printer.setPageSize(QPrinter.A4)
        printer.setPageMargins(margin, margin, margin, margin, QPrinter.Millimeter)
        printer.setResolution(96)

        doc = QTextDocument()
        doc.setUseDesignMetrics(True)
        doc.setDefaultFont(self.offer_font)
        doc.setHtml(self.offer.printout(print_options))
        doc.setPageSize(printer.pageRect().size())
        doc.print_(printer)
Exemple #9
0
    from PySide2.QtGui import QTextDocument
    from PySide2.QtPrintSupport import QPrinter
    from PySide2.QtWidgets import QTextEdit

    html = "<body><div align=center> Center </div>"
    html += "<div align=left> Left </div>"
    html += "<h1 align=center> Center title </h1>"
    html += "<p align=justify class=\"test1\"> {} </p>".format("Loren ipsum " *
                                                               1000)
    html += "<div align=right> End document </div></body>"

    document = QTextDocument()
    with open("style.css", "r") as fp:
        document.setDefaultStyleSheet(fp.read())
    document.setHtml(html)

    printer = QPrinter(QPrinter.PrinterResolution)
    printer.setOutputFormat(QPrinter.PdfFormat)
    printer.setPaperSize(QPrinter.A4)
    printer.setOutputFileName("file2.pdf")
    printer.setPageMargins(QMargins(10, 10, 10, 10))
    document.print_(printer)

    from PySide2.QtPrintSupport import QPrintPreviewWidget
    '''
    txtview = QTextEdit()
    txtview.setDocument(document)
    txtview.show()
    '''
Exemple #10
0
    def paint(self, painter: QPainter, option: QStyleOptionViewItem,
              index: QModelIndex):
        """
        Displays dirty files in red with corresponding rebuild buttons
        if in developer mode (is_dev_mode). Otherwise, renders normally


        Args:
            painter (QPainter): Current painter
            option (QStyleOptionViewItem): Current option
            index (QModelIndex): Current index of related model



        """
        if self.is_dev_mode:
            source_model = self.get_source_model(index.model(),
                                                 self.source_model_type)

            model = index.model()

            # get data of filename
            filename = str(
                model.data(
                    model.sibling(index.row(), source_model.FILENAME, index)))

            if source_model.is_file_dirty(filename):
                if index.column() == source_model.FILENAME:

                    text = filename
                    palette = option.palette
                    document = QTextDocument()
                    document.setDefaultFont(option.font)
                    document.setHtml(f"<font color={'red'}>{text}</font>")
                    background_color = palette.base().color()
                    painter.save()
                    painter.fillRect(option.rect, background_color)
                    painter.translate(option.rect.x(), option.rect.y())
                    document.drawContents(painter)
                    painter.restore()

                elif index.column() == source_model.REBUILD:
                    if '.py' in filename:
                        text = "rebuild"
                        palette = option.palette
                        document = QTextDocument()
                        # needed to add Right Alignment:  qt bug :
                        # https://bugreports.qt.io/browse/QTBUG-22851
                        document.setTextWidth(option.rect.width())
                        text_options = document.defaultTextOption()
                        text_options.setTextDirection(Qt.RightToLeft)
                        document.setDefaultTextOption(
                            text_options)  # get right alignment
                        document.setDefaultFont(option.font)
                        document.setHtml(
                            f'<font color={"red"}> <b> {text}</b> </font>')
                        background_color = palette.base().color()
                        painter.save()
                        painter.fillRect(option.rect, background_color)
                        painter.translate(option.rect.x(), option.rect.y())
                        document.drawContents(painter)
                        painter.restore()

            else:
                QItemDelegate.paint(self, painter, option, index)

        else:
            QItemDelegate.paint(self, painter, option, index)
    def saveOriginalAndTranslate(self):

        linesOriginalText = self.ui.plainTextEditOriginalText.toPlainText(
        ).split("\n")
        linesTranslateText = self.ui.plainTextEditTranslateText.toPlainText(
        ).split("\n")

        table = [linesOriginalText, linesTranslateText]
        filesTypes = "Plik tekstowy (*.txt);;Plik PDF (*.pdf)"

        name, filter = QFileDialog.getSaveFileName(self, 'Zapisz plik',
                                                   "Bez nazwy", filesTypes)

        if not name:
            return
        if filter == "Plik PDF (*.pdf)":
            try:
                try:
                    template = pd.DataFrame(table, dtype=str)
                    template = template.T
                    template.columns = ["Oryginał", "Tłumaczenie"]
                    html = template.to_html(index=False, border=0)
                    htmlFile = open("temp.html", "w", encoding="utf-8")
                    htmlFile.write(html)
                    htmlFile.close()
                except Exception as inst:
                    self.showErrorDialog(
                        "Problem podczas tworzenia szablonu PDF \n" +
                        str(inst))

                doc = QTextDocument()
                try:
                    html = open("temp.html", "r", encoding="utf-8")
                    doc.setHtml(html.read())
                except Exception as inst:
                    self.showErrorDialog("Problem z szablonem PDF \n" +
                                         str(inst))
                html.close()

                try:
                    printer = QPrinter()
                    printer.setOutputFileName(name)
                    printer.setOutputFormat(QPrinter.PdfFormat)
                    printer.setPageSize(QPrinter.A4)
                    printer.setPageMargins(4, 4, 4, 4, QPrinter.Millimeter)

                    doc.print_(printer)
                    os.remove('temp.html')
                except Exception as inst:
                    self.showErrorDialog("Problem z generowanie pliku PDF \n" +
                                         str(inst))
            except Exception as inst:
                self.showErrorDialog("Problem podczas zapisu pliku PDF \n" +
                                     str(inst))

        elif filter == "Plik tekstowy (*.txt)":
            try:
                file = open(name, "w", encoding='utf-8')
            except Exception as inst:
                self.showErrorDialog("Problem z wybranym plikiem \n" +
                                     str(inst))
            try:
                if len(linesOriginalText) >= len(linesTranslateText):
                    longer = linesOriginalText
                else:
                    longer = linesTranslateText
                for index in range(len(longer)):
                    if not linesOriginalText[index]:
                        linesOriginalText.append("")
                    if not linesTranslateText[index]:
                        linesTranslateText.append("")
                    if len(linesOriginalText[index]) == 0 and len(
                            linesTranslateText[index]) == 0:
                        file.write("\n")
                    else:
                        file.write(
                            str(linesOriginalText[index]) + "     -->     " +
                            str(linesTranslateText[index]) + "\n")
                file.close()
            except Exception as inst:
                self.showErrorDialog(
                    "Problem z tworzeniem pliku tekstowego \n" + str(inst))