Example #1
0
 def slot_print(self):
     printer = QPrintDialog(self.document_prt)
     if printer.exec() != QDialog.Accepted:
         return
     doc = QTextDocument()
     doc.setPlainText(self.editor.toPlainText())
     doc.print(self.document_prt)
Example #2
0
def SaveTableImage(table):
    pixmap = table.grab()
    pixmap.save("widget.png")
    SaveTableImage(table)

    nrows = table.rowCount()
    ncols = table.columnCount()
    doc = QTextDocument()
    cursor = QTextCursor(doc)
    tableFormat = QTextTableFormat()

    tableFormat.setHeaderRowCount(1)
    tableFormat.setAlignment(Qt.AlignHCenter)
    tableFormat.setCellPadding(0)
    tableFormat.setCellSpacing(0)
    tableFormat.setBorder(1)
    tableFormat.setBorderBrush(QBrush(Qt.SolidPattern))
    tableFormat.clearColumnWidthConstraints()

    textTable = cursor.insertTable(nrows + 1, ncols, tableFormat)
    tableHeaderFormat = QTextCharFormat()
    tableHeaderFormat.setBackground(QColor("#DADADA"))
    for i in range(ncols):
        cell = textTable.cellAt(0, i)
        cell.setFormat(tableHeaderFormat)
        cellCursor = cell.firstCursorPosition()
        cellCursor.insertText(table.horizontalHeaderItem(i).text())

    for i in range(nrows):
        for j in range(ncols):
            item = table.item(i, j)
            t = "" if item is None else str(item.text())
            # if item.text().iEmpty():
            #     table.setItem(i,j,QTableWidgetItem("0"))

            cell = textTable.cellAt(i + 1, j)
            cellCursor = cell.firstCursorPosition()
            cellCursor.insertText(t)

    cursor.movePosition(QTextCursor.End)
    printer = QPrinter(QPrinter.PrinterResolution)
    printer.setPaperSize(QPrinter.A4)
    printer.setOrientation(QPrinter.Landscape)
    printer.setOutputFileName("w8.pdf")
    doc.setDocumentMargin(0)
    doc.setTextWidth(5)
    doc.print(printer)
Example #3
0
 def Bqdy_func(self):
     html1 = self.Spgl_splr_ylxg.toHtml()
     p = QPrinterInfo.defaultPrinter()  # 获取默认打印机
     print_device = QPrinter(p)
     document = QTextDocument()
     lift_margin = self.Spgl_splr_pagelift_margin.text()
     right_margin = self.Spgl_splr_pageright_margin.text()
     print_device.setPageMargins(float(lift_margin), float(right_margin), 0,
                                 0, QPrinter.Millimeter)
     document.setPageSize(QSizeF(print_device.pageRect().size()))
     document.setHtml(html1)
     #实现按数量打印标签
     SPSL = self.Spgl_spsl.text()
     a = 1
     while a <= int(SPSL):
         document.print(print_device)
         a = a + 1
     self.Spgl_splr_ylxg.clear()
Example #4
0
class ReportDialog(QDialog, export_window.Ui_Dialog):
    """ Summary of ReportDialog.

    Represents a pop-up dialog when user presses "Export" button. Dialog contains a preview of the report containing
    values of "mu", "k", "R^2" and the replica of FiberFit main window's when a sample has been processed.

    Attributes:
        - do_print is a signal sent when either Save or Save All button are pressed.
        - do_excel is a signal starting the process of exporting results into an .csv format
        - sendDataList is a signal that sends a list containing already exported images back to FiberFit.
        - data_list is a list representing already exported images
        - screen_dim stores a screen dimension
        - document is an instance of QTextDocument that
       TODO: add other attributes.
    """
    do_print = pyqtSignal()
    do_excel = pyqtSignal()
    sendDataList = pyqtSignal(list)

    def __init__(self, fft_mainWindow,parent=None, screenDim=None):

        super(ReportDialog, self).__init__(parent)
        self.fft_mainWindow=fft_mainWindow
        self.dataList = []
        self.setupUi(self, screenDim)
        self.screenDim = screenDim
        self.document = QTextDocument()
        #list that keeps track of only selected images
        self.list = []
        #list that contains all of the stored images
        self.wholeList = OrderedSet()
        self.savedfiles = None
        self.currentModel = None
        # settings
        self.uCut = 0
        self.lCut = 0
        self.angleInc = 0
        self.radStep = 0
        #  states
        """
        0 -> single
        1 -> multiple
        2 -> append
        """
        self.isReport = True
        self.isSummary = False
        self.reportOption = 2
        self.merger = merger()
        # printer
        self.printer = QPrinter(QPrinter.PrinterResolution)
        # Signals and slots:
        self.do_excel.connect(self.exportExcel)
        self.webView = QtWebKitWidgets.QWebView()

        # self.checkBox_report.stateChanged.connect(self.topLogicHandler)
        self.checkBox_summary.stateChanged.connect(self.topLogicHandler)

        self.radio_multiple.toggled.connect(self.toggleHandler)
        self.radio_single.toggled.connect(self.toggleHandler)
        self.radio_append.toggled.connect(self.toggleHandler)

        self.buttonBox.button(QDialogButtonBox.Ok).clicked.connect(self.exportHandler)
        self.do_print.connect(self.print)
        self.rejected.connect(self.resetOptions)
        self.topLogicHandler()

    def resetOptions(self):
        self.checkBox_summary.setChecked(False)
        self.radio_append.setChecked(True)
        self.radio_multiple.setChecked(False)
        self.radio_single.setChecked(False)

    def exportHandler(self):
        if self.isSummary and self.isReport is False:
            self.saveas()
        elif (self.reportOption == 0 or self.reportOption == 2 or self.reportOption == 1) and self.isSummary is False:
            self.saveas()
        elif self.isSummary and self.isReport:
            self.saveas()

    def toggleHandler(self):
        if self.radio_single.isChecked():
            self.reportOption = 0
            self.isReport = True
            self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)
        elif self.radio_multiple.isChecked():
            self.reportOption = 1
            self.isReport = True
            self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)
        elif self.radio_append.isChecked():
            self.reportOption = 2
            self.isReport = True
            self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)
        elif self.radio_none.isChecked():
            self.reportOption = -1
            self.isReport = False
            if (not self.checkBox_summary.isChecked()):
                self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)

    def topLogicHandler(self):
        if self.checkBox_summary.isChecked():
            self.isSummary = True
            self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)
        elif self.checkBox_summary.isChecked() is False:
            self.isSummary = False
            if (self.radio_none.isChecked()):
                self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)

    @pyqtSlot()
    def exportExcel(self):
        if self.dataList.__len__() == 0:
            self.dataList.append(
                [self.wholeList[0].filename.stem,
                 self.uCut,
                 self.lCut,
                 self.radStep,
                 self.angleInc,
                 self.wholeList[0].sig,
                 self.wholeList[0].th,
                 self.wholeList[0].k,
                 self.wholeList[0].R2,
                 self.wholeList[0].timeStamp])
        temp = []
        for i in range(0, self.wholeList.__len__()):
            temp.append(self.wholeList[i])
        for i in range(0, len(self.dataList)):
            found = False
            for j in range(0, len(temp)):
                # One image from list is at most can equal to one another image from temp
                if found is False and self.dataList[i][0] == temp[j].filename.stem:
                    self.dataList.remove(self.dataList[i])
                    self.dataList.insert(i, [temp[j].filename.stem,
                                             self.uCut,
                                             self.lCut,
                                             self.radStep,
                                             self.angleInc,
                                             round(temp[j].sig[0], 2),
                                             round(temp[j].th, 2),
                                             round(temp[j].k, 2),
                                             round(temp[j].R2, 2),
                                             temp[j].timeStamp])
                    temp.remove(temp[j])
                    found = True
        for k in range(0, len(temp)):
            self.dataList.append([temp[k].filename.stem,
                                  self.uCut,
                                  self.lCut,
                                  self.radStep,
                                  self.angleInc,
                                  round(temp[k].sig[0], 2),
                                  round(temp[k].th, 2),
                                  round(temp[k].k, 2),
                                  round(temp[k].R2, 2),
                                  temp[k].timeStamp])
        with open(str(self.savedfiles.parents[0]) + '/summary.csv', 'w') as csvfile:
            a = csv.writer(csvfile)
            a.writerow(['Name', 'LowerCut', 'UpperCut', 'RadialStep', 'AngleIncrement', 'Sig', 'Mu', 'K', 'R^2', 'Time'])
            a.writerows(self.dataList)
        self.fft_mainWindow.dataList = self.dataList

    def saveas(self):
        """
        Pops out a dialog allowing user to select where to save the image.
        """
        dialog = QFileDialog()
        if (self.reportOption == 0):
            self.savedfiles = pathlib.Path(dialog.getSaveFileName(self, "Export", self.currentModel.filename.stem)[0])
            self.close()
        elif (self.reportOption == 1):
            self.savedfiles = pathlib.Path(dialog.getSaveFileName(self, "Export",
                                                                  "Image Name")[0])
            self.close()
        elif (self.reportOption == 2):
            self.savedfiles = pathlib.Path(dialog.getSaveFileName(self, "Export",
                                                                  "Report")[0])
            self.close()
        if (self.isSummary and not self.isReport):
            self.savedfiles = pathlib.Path(dialog.getSaveFileName(self, "Export",
                                                                  "SummaryTable")[0])
        self.printerSetup()
        if (self.isReport == True):
            self.do_print.emit()
        if self.isSummary == True:
            self.do_excel.emit()

    def print(self):
        """
        Checks which button sent a signal. Based on that it either prints all images or just a single specific image.
        """
        if (self.reportOption == 1):
            for model in self.wholeList:
                self.document.setHtml(self.createHtml(model, forPrinting=True))
                self.printer.setOutputFileName(
                    self.savedfiles.parents[0].__str__() + '/' + self.savedfiles.name.replace("Image Name", "") + model.filename.stem + '.pdf')
                self.document.print(self.printer)
        elif (self.reportOption == 0):
            self.document.print(self.printer)

        elif (self.reportOption == 2):
            self.merger = merger()
            for model in self.wholeList:
                self.document.setHtml(self.createHtml(model, forPrinting=True))
                name = self.savedfiles.__str__() + '.pdf'
                print(name)
                self.printer.setOutputFileName(
                    self.savedfiles.parents[0].__str__() + '/' + self.savedfiles.name.replace("Image Name", "") + model.filename.stem + '.pdf')
                self.document.print(self.printer)
                input = open(self.savedfiles.parents[0].__str__() + '/' + self.savedfiles.name.replace("Image Name", "") + model.filename.stem + '.pdf', "rb")
                self.merger.append(input)
                os.remove(self.savedfiles.parents[0].__str__() + '/' + self.savedfiles.name.replace("Image Name", "") + model.filename.stem + '.pdf')

            out = open(name, "wb")
            self.merger.write(out)
            self.merger.close()

    def printerSetup(self):
        """
        Sets up default instructions for printer.
        """
        self.printer.setPageSize(QPrinter.Letter)
        self.printer.setOutputFormat(QPrinter.PdfFormat)
        self.printer.setFullPage(True)
        self.printer.setOutputFileName(str(self.savedfiles)+".pdf")

    def createHtml(self, model, forPrinting):
        """
        Creates html-based report that shows the basic information about the sample.
        """
        # for printing
        if forPrinting:
            html = """
        <html>
            <head>
                <link type="text/css" rel="stylesheet" href="ntm_style.css"/>
            </head>
            <body>
                <p> Image Name: {name} </p> <p> μ: {th}° </p>
                <p>k: {k} </p>
                <p>R^2: {R2} </p>
                <p>σ: {sig}°</p>
                <br>
                <table>
                    <tr>
                        <td> <img src = "data:image/png;base64,{encodedOrgImg}" width = "250", height = "250" /></td>
                        <td> <img src ="data:image/png;base64,{encodedLogScl}" width = "250", height = "250"/></td>
                    </tr>
                    <tr>
                        <td> <img src = "data:image/png;base64,{encodedAngDist}" width = "250", height = "250" /></td>
                        <td> <img src = "data:image/png;base64,{encodedCartDist}" width = "250", height = "250" /></td>
                    </tr>
                </table>
                <p><br><br>
                    {date}
                </p>
            </body>
        </html>
        """.format(name=model.filename.stem, th=round(model.th, 2), k=round(model.k, 2), R2=round(model.R2, 2),
                   sig = round(model.sig[0], 2),
                   encodedOrgImg=model.orgImgEncoded.translate('bn\''),
                   encodedLogScl=model.logSclEncoded.translate('bn\''),
                   encodedAngDist=model.angDistEncoded.translate('bn\''),
                   encodedCartDist=model.cartDistEncoded.translate('bn\''),
                   date=model.timeStamp)
            return html

    @pyqtSlot(img_model.ImgModel)
    def do_test(self, model):
        """
        Makes report for an image that was active when user pressed Export button.
        """
        self.webView.setHtml(self.createHtml(model, False))
        self.document.setHtml(self.createHtml(model, True))
        self.currentModel = model
        self.show()

    @pyqtSlot(list, list, OrderedSet, float, float, float, float)
    def receiver(self, selectedImgs, dataList, imgList, uCut, lCut, radStep, angleInc):
        """
        Received an information from FiberFit applicatin with necessary report data.
        """
        self.dataList = dataList
        self.list = selectedImgs
        self.wholeList = imgList
        self.uCut = uCut
        self.lCut = lCut
        self.radStep = radStep
        self.angleInc = angleInc
Example #5
0
class ReportDialog(QDialog, export_window.Ui_Dialog):
    """ Summary of ReportDialog.

    Represents a pop-up dialog when user presses "Export" button. Dialog contains a preview of the report containing
    values of "mu", "k", "R^2" and the replica of FiberFit main window's when a sample has been processed.

    Attributes:
        - do_print is a signal sent when either Save or Save All button are pressed.
        - do_excel is a signal starting the process of exporting results into an .csv format
        - sendDataList is a signal that sends a list containing already exported images back to FiberFit.
        - data_list is a list representing already exported images
        - screen_dim stores a screen dimension
        - document is an instance of QTextDocument that
       TODO: add other attributes.
    """
    do_print = pyqtSignal()
    do_excel = pyqtSignal()
    sendDataList = pyqtSignal(list)

    def __init__(self, fft_mainWindow, parent=None, screenDim=None):

        super(ReportDialog, self).__init__(parent)
        self.fft_mainWindow = fft_mainWindow
        self.dataList = []
        self.setupUi(self, screenDim)
        self.screenDim = screenDim
        self.document = QTextDocument()
        #list that keeps track of only selected images
        self.list = []
        #list that contains all of the stored images
        self.wholeList = OrderedSet()
        self.savedfiles = None
        self.currentModel = None
        # settings
        self.uCut = 0
        self.lCut = 0
        self.angleInc = 0
        self.radStep = 0
        #  states
        """
        0 -> single
        1 -> multiple
        2 -> append
        """
        self.isReport = True
        self.isSummary = False
        self.reportOption = 2
        self.merger = merger()
        # printer
        self.printer = QPrinter(QPrinter.PrinterResolution)
        # Signals and slots:
        self.do_excel.connect(self.exportExcel)
        self.webView = QtWebKitWidgets.QWebView()

        # self.checkBox_report.stateChanged.connect(self.topLogicHandler)
        self.checkBox_summary.stateChanged.connect(self.topLogicHandler)

        self.radio_multiple.toggled.connect(self.toggleHandler)
        self.radio_single.toggled.connect(self.toggleHandler)
        self.radio_append.toggled.connect(self.toggleHandler)

        self.buttonBox.button(QDialogButtonBox.Ok).clicked.connect(
            self.exportHandler)
        self.do_print.connect(self.print)
        self.rejected.connect(self.resetOptions)
        self.topLogicHandler()

    def resetOptions(self):
        self.checkBox_summary.setChecked(False)
        self.radio_append.setChecked(True)
        self.radio_multiple.setChecked(False)
        self.radio_single.setChecked(False)

    def exportHandler(self):
        if self.isSummary and self.isReport is False:
            self.saveas()
        elif (self.reportOption == 0 or self.reportOption == 2
              or self.reportOption == 1) and self.isSummary is False:
            self.saveas()
        elif self.isSummary and self.isReport:
            self.saveas()

    def toggleHandler(self):
        if self.radio_single.isChecked():
            self.reportOption = 0
            self.isReport = True
            self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)
        elif self.radio_multiple.isChecked():
            self.reportOption = 1
            self.isReport = True
            self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)
        elif self.radio_append.isChecked():
            self.reportOption = 2
            self.isReport = True
            self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)
        elif self.radio_none.isChecked():
            self.reportOption = -1
            self.isReport = False
            if (not self.checkBox_summary.isChecked()):
                self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)

    def topLogicHandler(self):
        if self.checkBox_summary.isChecked():
            self.isSummary = True
            self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)
        elif self.checkBox_summary.isChecked() is False:
            self.isSummary = False
            if (self.radio_none.isChecked()):
                self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)

    @pyqtSlot()
    def exportExcel(self):
        if self.dataList.__len__() == 0:
            self.dataList.append([
                self.wholeList[0].filename.stem, self.uCut, self.lCut,
                self.radStep, self.angleInc, self.wholeList[0].sig,
                self.wholeList[0].th, self.wholeList[0].k,
                self.wholeList[0].R2, self.wholeList[0].timeStamp
            ])
        temp = []
        for i in range(0, self.wholeList.__len__()):
            temp.append(self.wholeList[i])
        for i in range(0, len(self.dataList)):
            found = False
            for j in range(0, len(temp)):
                # One image from list is at most can equal to one another image from temp
                if found is False and self.dataList[i][0] == temp[
                        j].filename.stem:
                    self.dataList.remove(self.dataList[i])
                    self.dataList.insert(i, [
                        temp[j].filename.stem, self.uCut, self.lCut,
                        self.radStep, self.angleInc,
                        round(temp[j].sig[0], 2),
                        round(temp[j].th, 2),
                        round(temp[j].k, 2),
                        round(temp[j].R2, 2), temp[j].timeStamp
                    ])
                    temp.remove(temp[j])
                    found = True
        for k in range(0, len(temp)):
            self.dataList.append([
                temp[k].filename.stem, self.uCut, self.lCut, self.radStep,
                self.angleInc,
                round(temp[k].sig[0], 2),
                round(temp[k].th, 2),
                round(temp[k].k, 2),
                round(temp[k].R2, 2), temp[k].timeStamp
            ])
        with open(str(self.savedfiles.parents[0]) + '/summary.csv',
                  'w') as csvfile:
            a = csv.writer(csvfile)
            a.writerow([
                'Name', 'LowerCut', 'UpperCut', 'RadialStep', 'AngleIncrement',
                'Sig', 'Mu', 'K', 'R^2', 'Time'
            ])
            a.writerows(self.dataList)
        self.fft_mainWindow.dataList = self.dataList

    def saveas(self):
        """
        Pops out a dialog allowing user to select where to save the image.
        """
        dialog = QFileDialog()
        if (self.reportOption == 0):
            self.savedfiles = pathlib.Path(
                dialog.getSaveFileName(self, "Export",
                                       self.currentModel.filename.stem)[0])
            self.close()
        elif (self.reportOption == 1):
            self.savedfiles = pathlib.Path(
                dialog.getSaveFileName(self, "Export", "Image Name")[0])
            self.close()
        elif (self.reportOption == 2):
            self.savedfiles = pathlib.Path(
                dialog.getSaveFileName(self, "Export", "Report")[0])
            self.close()
        if (self.isSummary and not self.isReport):
            self.savedfiles = pathlib.Path(
                dialog.getSaveFileName(self, "Export", "SummaryTable")[0])
        self.printerSetup()
        if (self.isReport == True):
            self.do_print.emit()
        if self.isSummary == True:
            self.do_excel.emit()

    def print(self):
        """
        Checks which button sent a signal. Based on that it either prints all images or just a single specific image.
        """
        if (self.reportOption == 1):
            for model in self.wholeList:
                self.document.setHtml(self.createHtml(model, forPrinting=True))
                self.printer.setOutputFileName(
                    self.savedfiles.parents[0].__str__() + '/' +
                    self.savedfiles.name.replace("Image Name", "") +
                    model.filename.stem + '.pdf')
                self.document.print(self.printer)
        elif (self.reportOption == 0):
            self.document.print(self.printer)

        elif (self.reportOption == 2):
            self.merger = merger()
            for model in self.wholeList:
                self.document.setHtml(self.createHtml(model, forPrinting=True))
                name = self.savedfiles.__str__() + '.pdf'
                print(name)
                self.printer.setOutputFileName(
                    self.savedfiles.parents[0].__str__() + '/' +
                    self.savedfiles.name.replace("Image Name", "") +
                    model.filename.stem + '.pdf')
                self.document.print(self.printer)
                input = open(
                    self.savedfiles.parents[0].__str__() + '/' +
                    self.savedfiles.name.replace("Image Name", "") +
                    model.filename.stem + '.pdf', "rb")
                self.merger.append(input)
                os.remove(self.savedfiles.parents[0].__str__() + '/' +
                          self.savedfiles.name.replace("Image Name", "") +
                          model.filename.stem + '.pdf')

            out = open(name, "wb")
            self.merger.write(out)
            self.merger.close()

    def printerSetup(self):
        """
        Sets up default instructions for printer.
        """
        self.printer.setPageSize(QPrinter.Letter)
        self.printer.setOutputFormat(QPrinter.PdfFormat)
        self.printer.setFullPage(True)
        self.printer.setOutputFileName(str(self.savedfiles) + ".pdf")

    def createHtml(self, model, forPrinting):
        """
        Creates html-based report that shows the basic information about the sample.
        """
        # for printing
        if forPrinting:
            html = """
        <html>
            <head>
                <link type="text/css" rel="stylesheet" href="ntm_style.css"/>
            </head>
            <body>
                <p> Image Name: {name} </p> <p> μ: {th}° </p>
                <p>k: {k} </p>
                <p>R^2: {R2} </p>
                <p>σ: {sig}°</p>
                <br>
                <table>
                    <tr>
                        <td> <img src = "data:image/png;base64,{encodedOrgImg}" width = "250", height = "250" /></td>
                        <td> <img src ="data:image/png;base64,{encodedLogScl}" width = "250", height = "250"/></td>
                    </tr>
                    <tr>
                        <td> <img src = "data:image/png;base64,{encodedAngDist}" width = "250", height = "250" /></td>
                        <td> <img src = "data:image/png;base64,{encodedCartDist}" width = "250", height = "250" /></td>
                    </tr>
                </table>
                <p><br><br>
                    {date}
                </p>
            </body>
        </html>
        """.format(name=model.filename.stem,
                   th=round(model.th, 2),
                   k=round(model.k, 2),
                   R2=round(model.R2, 2),
                   sig=round(model.sig[0], 2),
                   encodedOrgImg=model.orgImgEncoded.translate('bn\''),
                   encodedLogScl=model.logSclEncoded.translate('bn\''),
                   encodedAngDist=model.angDistEncoded.translate('bn\''),
                   encodedCartDist=model.cartDistEncoded.translate('bn\''),
                   date=model.timeStamp)
            return html

    @pyqtSlot(img_model.ImgModel)
    def do_test(self, model):
        """
        Makes report for an image that was active when user pressed Export button.
        """
        self.webView.setHtml(self.createHtml(model, False))
        self.document.setHtml(self.createHtml(model, True))
        self.currentModel = model
        self.show()

    @pyqtSlot(list, list, OrderedSet, float, float, float, float)
    def receiver(self, selectedImgs, dataList, imgList, uCut, lCut, radStep,
                 angleInc):
        """
        Received an information from FiberFit applicatin with necessary report data.
        """
        self.dataList = dataList
        self.list = selectedImgs
        self.wholeList = imgList
        self.uCut = uCut
        self.lCut = lCut
        self.radStep = radStep
        self.angleInc = angleInc
 def handlePaintRequest(self, printer):
     document = QTextDocument()
     cursor = QTextCursor(document)
     cursor.insertText(self.label.text())
     document.print(printer)
Example #7
0
def print_html(printer):
    root = 'config.ini'
    basic_msg = configparser.ConfigParser()
    basic_msg.read(root)
    try:
        if not myconnect:
            raise TimeoutError
        code = basic_msg.get("msg", 'code')
        url = domain + "store/api/detail?code={}".format(code)
        req = requests.get(url=url)
        result_data = json.loads(req.text)
    except Exception as e:
        print(e)

        store = config.get_local_store_info()

        result_data = {
            'data': {
                "pcId": store.id(),
                "pcPhone": store.phone(),
                "pcAddress": store.address(),
                "pcSign": store.name(),
            },
            'code': 200
        }
    must_set = ['数量', '单价', '小计', '总价', '单位', '备注']

    if result_data.get("code") != 200:
        store_name = ""
        pc_address = ""
        pc_phone = ""
    else:
        store_name = result_data.get("data").get("pcSign", "")
        pc_address = result_data.get("data").get("pcAddress", "")
        pc_phone = result_data.get("data").get("pcPhone", "")
    result = get_sale_info_by_one_key(selectOrderNo)

    fp = open("printer.txt", 'rb')
    data = fp.readline().decode().replace("\n", "").replace("\r", "").replace("\ufeff", "")
    fp.close()
    font_size = 7
    if data:
        try:
            font_size = int(data)
        except Exception as e:
            print(e)
            font_size = 7

    # *{font-size:65px;}
    if result:
        header = """<html>
            <style>
            table{
                background-color:#000000;
            }

            .linetd{
                text-align: center;
                width: 820px;
                color: red;
                height: 30px;
            }

            .halftd{
                width: 410px;
            }

            #content{
                text-align: center;
                position: relative;
                top: 50%;
                transform: translateY(-50%);
            }

            td{
                padding:2px;
                align:center;
                border:1px solid black;
                background-color:#ffffff
            }

        """ + "*{font-size:" + str(font_size) + "pt;}" + ".bigWord{font-size:" + str(
            font_size * 1.5) + "pt;}" + "</style><head></head>"
        # *{font-size:50px;}
        td_width = 19
        body = """
            <body style="text-align: center;">
                <table width=100% CELLPADDING="0" CELLSPACING="1" border="0">
                    <tr>
                        <td class="bigWord" align="center" colspan="100" width="100%">
                            {storeName}
                        </td>
                    </tr>
                    <tr>
                        <td colspan="50">车牌号:{carId}</td>
                        <td colspan="50">销售日期:{createdTime}</td>
                    </tr>
                    <tr>
                        <td colspan="50">客户电话:{carPhone}</td>
                        <td colspan="50">销售单号:<span style="">{orderNo}</span></td>
                    </tr>
                    <tr>
                        <td colspan="100" height="20px"> </td>
                    </tr>

                    """.format(storeName=store_name, carId=result[0][2], createdTime=result[0][0],
                               carPhone=result[0][4],
                               orderNo=result[0][1])

        content = ""
        seq = 1
        total_price = 0
        page = 0
        page_height = 100
        for order in result:
            page += 1
            attribute = json.loads(order[8])
            base_height = 180
            # 手动排序
            # mustSet = ['数量','单价','小计','总价','单位','备注']
            # 去除mustset后的必然顺序为:"品牌","型号","工时费","更换里程"
            # 后面用字符串排序key来排序
            temp_key_list2 = ["品牌", "型号", "工时费", "更换里程"]
            temp_key_list = list()
            for t in temp_key_list2:
                if attribute.get(t) and attribute.get(t) != '-':
                    temp_key_list.append(t)

            for k, v in attribute.items():
                if k not in must_set + ["品牌", "型号", "工时费", "更换里程"] and v != "-" and v != "" and k != "检索ID":
                    temp_key_list.append(k)
            temp_key_list.sort()
            no_must_set = OrderedDict()
            for k in temp_key_list:
                no_must_set[k] = attribute.get(k)
            # 总长度要减去备注和名称,因为名称长度另外设置,备注不打印
            td = ""
            key_dict = dict()
            i = 0
            j = 0
            td_list = list()
            key_list = list()
            page_height += int(len(no_must_set.keys()) / 5 + 1) * 60 + base_height
            for k, v in no_must_set.items():
                # if k not in mustSet and v != "-"  and v != "" and k!="检索ID" :
                td += "<td colspan=\"{tdWidth}\" align=\"center\"><b>{key}</b></td>".format(tdWidth=td_width, key=k)
                key_list.append(k)
                if i >= 4:
                    i = 0
                    td_list.append(td)
                    td = ""
                    key_dict[j] = key_list
                    key_list = list()
                    j += 1
                else:
                    i += 1

            # 补齐
            if key_list:
                if len(key_list) < 5:
                    num = len(key_list)
                    for i in range(5 - num):
                        key_list.append("")
                        td += "<td colspan=\"{tdWidth}\" align=\"center\"></td>".format(tdWidth=td_width)
                td_list.append(td)
                key_dict[j] = key_list
            # 序号合并列数
            merge_num = len(td_list) * 2 + 2
            # createdTime,orderNo,carId,carUser,carPhone,carModel,workerName,project,brand," \
            # "model,huawen,number,unitPrice,xiaoji,gongshi,ghlc,remark,totalPrice,pcId,unit
            content += """
                <tr>
                        <td colspan="5" align="center"><b>序</b></td>
                        <td colspan="{tdWidth}" align="center"><b>名称</b></td>
                        <td colspan="{tdWidth}" align="center"><b>单位</b></td>
                        <td colspan="{tdWidth}" align="center"><b>数量</b></td>
                        <td colspan="{tdWidth}" align="center"><b>单价</b></td>
                        <td colspan="{tdWidth}" align="center"><b>小计</b></td>
                    </tr>
                <tr>
                    <td rowspan="{xuNum}" colspan="5" align="center"><br/>{xuhao}</td>
                    <td colspan="{tdWidth}" align="center">{project}</td>
                    <td colspan="{tdWidth}" align="center">{unit}</td>
                    <td colspan="{tdWidth}" align="center">{number}</td>
                    <td colspan="{tdWidth}" align="center">{unitPrice}</td>
                    <td colspan="{tdWidth}" align="center">{xiaoji}</td>
                </tr>

            """.format(xuNum=merge_num, xuhao=seq, unit=attribute.get("单位", ""), number=attribute.get("数量", ""),
                       unitPrice=attribute.get("单价", ""),
                       xiaoji=attribute.get('小计', ""), project=order[7], tdWidth=td_width)

            more_content = ""
            ii = 0
            for td in td_list:
                # 先放入表头
                more_content += "<tr>" + td + "</tr>"
                # 再放入内容
                more_content += """
                    <tr>
                    <td colspan="{tdWidth}" align="center">{one}</td>
                    <td colspan="{tdWidth}" align="center">{two}</td>
                    <td colspan="{tdWidth}" align="center">{three}</td>
                    <td colspan="{tdWidth}" align="center">{four}</td>
                    <td colspan="{tdWidth}" align="center">{five}</td>
                    </tr>
                """.format(tdWidth=td_width, one=attribute.get(key_dict[ii][0], ""),
                           two=attribute.get(key_dict[ii][1], ""),
                           three=attribute.get(key_dict[ii][2], ""), four=attribute.get(key_dict[ii][3], ""),
                           five=attribute.get(key_dict[ii][4], ""))

                ii += 1
            fenge = """
            <tr>
                <td colspan="100" height="20px"> </td>
            </tr>
                """

            zongjiaconetent = """
                <tr>
                    <td colspan="95">总价:{zongjia}</td>
                </tr>
            """.format(zongjia=attribute.get('总价', ""))
            content += more_content + zongjiaconetent + fenge
            seq += 1
            try:
                total_price += float(attribute.get('总价', 0))
            except Exception as e:
                print(e)
                total_price = 0

        total_price = str(total_price)
        cn = cncurrency(total_price)

        foot = """
            <tr>
                <td style="height:35px" colspan="70">合计人名币(大写):{cn}</td>
                <td style="height:35px"  colspan="30">小写:{zongjia}</td>
            </tr>
            <tr>
                <td colspan="30">{storeName}</td>
                <td colspan="35">地址:{pcAddress}</td>
                <td colspan="35">联系电话:{pcPhone}</td>
            </tr>
        </table>
        </body>
        </html>
        """.format(cn=cn, zongjia=total_price, storeName=store_name, pcPhone=pc_phone, pcAddress=pc_address)

        html = header + body + content + foot
        text_document = QTextDocument()
        text_document.setHtml(html)
        text_document.setDocumentMargin(35)
        printer.setPageSize(QPrinter.Custom)
        # height = baseHeight+((page-1)*150)
        # printer.setPaperSize(QSizeF(printer.logicalDpiX()*(86/25.4),height),QPrinter.Point)
        # textDocument.setPageSize(QSizeF(printer.logicalDpiX()*(86/25.4),height))
        printer.setPaperSize(QSizeF(581, page_height), QPrinter.Point)
        text_document.setPageSize(QSizeF(581, page_height))
        textOp = QTextOption()
        textOp.setWrapMode(QTextOption.WrapAnywhere)
        textOp.setAlignment(Qt.AlignCenter)
        text_document.setDefaultTextOption(textOp)
        printer.setOutputFormat(QPrinter.NativeFormat)
        text_document.print(printer)
Example #8
0
    def save_as_pdf(self):
        filename = QFileDialog.getSaveFileName(self, 'Save to PDF', 'c:\\',
                                               "*.pdf")

        if filename != ('', ''):
            if os.path.exists(filename[0]):
                try:
                    infile = PdfFileReader(filename[0], 'rb')
                except:
                    error = QMessageBox()
                    error.setIcon(QMessageBox.Warning)
                    error.setStandardButtons(QMessageBox.Ok)
                    error.setText(
                        "File could not be written to. If the file is currently open, try closing it"
                    )
                    error.exec_()
                    return
                if infile.getNumPages() == 0:
                    print("HERE!")
                    doc = QTextDocument()
                    doc.print(printer)

            printer = QPrinter()
            printer.setPageSize(QPrinter.A4)
            printer.setOutputFormat(QPrinter.PdfFormat)
            printer.setOutputFileName(filename[0])

            painter = QPainter()

            font = QFont("times")
            font.setPointSize(12)

            x = painter.begin(printer)
            if x == False:
                error = QMessageBox()
                error.setIcon(QMessageBox.Warning)
                error.setStandardButtons(QMessageBox.Ok)
                error.setText(
                    "File could not be saved. If the file is currently open, try closing it"
                )
                error.exec_()
                return
            painter.setFont(font)

            for i in range(0, self.symbol_tests.count()):
                cur_symbol_test = self.symbol_tests.widget(i)

                if cur_symbol_test.print_visual_context() == False:
                    pixmap = cur_symbol_test.get_symbol()
                    pixmap = pixmap.scaled(350, 350)

                    painter.drawPixmap(30, 100, pixmap)
                    painter.drawText(750, 20, cur_symbol_test.get_page())
                    painter.drawText(
                        420, 200, 350, 400, QtCore.Qt.TextWordWrap,
                        "Context: " + cur_symbol_test.get_context())
                    painter.drawText(30, 600, cur_symbol_test.get_question1())
                    painter.drawText(30, 830, cur_symbol_test.get_question2())

                    cur_pen = painter.pen()
                    line_pen = QPen()
                    line_pen.setWidth(2)
                    painter.setPen(line_pen)
                    painter.drawLine(70, 656, 600, 656)
                    painter.drawLine(70, 712, 600, 712)
                    painter.drawLine(70, 768, 600, 768)

                    painter.drawLine(70, 886, 600, 886)
                    painter.drawLine(70, 942, 600, 942)
                    painter.drawLine(70, 998, 600, 998)
                    painter.setPen(cur_pen)

                else:
                    pixmap = cur_symbol_test.get_visual_context()
                    pixmap = pixmap.scaled(300, 300)

                    painter.drawPixmap(200, 10, pixmap)

                    pixmap = cur_symbol_test.get_symbol()
                    pixmap = pixmap.scaled(250, 250)

                    painter.drawPixmap(225, 320, pixmap)

                    painter.drawText(750, 20, cur_symbol_test.get_page())
                    #painter.drawText(420, 200, 350, 400, QtCore.Qt.TextWordWrap, "Context: " + cur_symbol_test.get_context())
                    painter.drawText(30, 600, cur_symbol_test.get_question1())
                    painter.drawText(30, 830, cur_symbol_test.get_question2())

                    cur_pen = painter.pen()
                    line_pen = QPen()
                    line_pen.setWidth(2)
                    painter.setPen(line_pen)
                    painter.drawLine(70, 656, 600, 656)
                    painter.drawLine(70, 712, 600, 712)
                    painter.drawLine(70, 768, 600, 768)

                    painter.drawLine(70, 886, 600, 886)
                    painter.drawLine(70, 942, 600, 942)
                    painter.drawLine(70, 998, 600, 998)
                    painter.setPen(cur_pen)
                if (i < self.symbol_tests.count() - 1):
                    printer.newPage()

            painter.end()
Example #9
0
    def on_actionDocumentReport_triggered(self):
        QApplication.setOverrideCursor(Qt.WaitCursor)

        doc = QTextDocument()
        comment = self.documents.selected.comment.replace("\n\n\n", "<p>")
        comment = comment.replace("\n\n", "<p>")
        comment = comment.replace("\n", "<p>")

        s = (
            "<center><h1>" + self.tr("DidYouReadMe Report") + "</h1>" +
            self.tr("Generation time") +
            ": {0}".format(str(now(self.mem.localzone))[:19]) + "</center>" +
            "<h2>" + self.tr("Document data") + "</h2>" + self.tr("Created") +
            ": {0}".format(str(self.documents.selected.datetime)[:19]) +
            "<p>" + self.tr("name") +
            ": {0}".format(self.documents.selected.name) + "<p>" +
            self.tr("Internal id") +
            ": {0}".format(self.documents.selected.id) + "<p>" +
            self.tr("Filename") +
            ": <a href='http://{0}:{1}/get/adminl{2}/{3}'>{4}</a><p>".format(
                self.mem.settings.value("webserver/ip", "127.0.0.1"),
                self.mem.settings.value("webserver/port", "8000"),
                self.documents.selected.hash,
                urllib.parse.quote(
                    os.path.basename(
                        self.documents.selected.filename.lower())),
                os.path.basename(self.documents.selected.filename)) +
            self.tr("File size") +
            ": {0}".format(self.documents.selected.getSize()) + "<p>" +
            self.tr("Comment") + ": {0}".format(comment) + "<p>" + "<h2>" +
            self.tr("User reads") + "</h2>" +
            "<p><table border='1'><thead><tr><th>{0}</th><th>{1}</th><th>{2}</th><th>{3}</th></tr></thead>"
            .format(self.tr("User"), self.tr("Sent"), self.tr("First read"),
                    self.tr("Number of reads")))

        cur = self.mem.con.cursor()
        cur.execute(
            "select * from users, userdocuments where id_documents=%s and userdocuments.id_users=users.id order by name",
            (self.documents.selected.id, ))
        for row in cur:
            s = s + "<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td></tr>".format(
                row['name'],
                str(row['sent'])[:19],
                str(row['read'])[:19], row['numreads'])
        s = s + "</table><p>"
        cur.close()

        doc.setHtml(s)
        printer = QPrinter()
        file = dirTmp + "{0} DidYouReadMe document.pdf".format(
            str(self.documents.selected.datetime)[:16]).replace(
                ":", "").replace("-", "")
        self.mem.log(
            self.tr("Document {} report was generated in {}".format(
                self.documents.selected.id, file)))
        printer.setOutputFileName(file)
        printer.setOutputFormat(QPrinter.PdfFormat)
        doc.print(printer)
        printer.newPage()

        self.openWithDefaultApp(file)
        QApplication.restoreOverrideCursor()