Exemplo n.º 1
0
    def filePrintPdf(self):
        fn, _ = QFileDialog.getSaveFileName(self, "Export PDF", None, "PDF files (*.pdf);;All Files (*)")

        if fn:
            if QFileInfo(fn).suffix().isEmpty():
                fn += ".pdf"

            printer = QPrinter(QPrinter.HighResolution)
            printer.setOutputFormat(QPrinter.PdfFormat)
            printer.setOutputFileName(fn)
            self.textEdit.document().print_(printer)
Exemplo n.º 2
0
 def actionPrintSlot(self) -> None:
     printer = QPrinter()
     printer.setPageOrientation(QPageLayout.Landscape)
     if QPrintDialog(printer).exec_():
         painter = QPainter(printer)
         painter.setRenderHint(QPainter.Antialiasing)
         view = QGraphicsView()
         view.setScene(self.scene)
         view.setSceneRect(QRectF(0, 0, 290, 200))
         view.fitInView(QRectF(0, 0, 290, 200), Qt.KeepAspectRatio)
         view.scale(1, -1)
         view.render(painter)
         del painter  # necessary, thanks Qt
Exemplo n.º 3
0
 def printPdf(self, frame):
      element = self.getPostElement(frame.documentElement())
      if element is not None:
         rect = element.geometry()
         pdf = QPrinter(QPrinter.ScreenResolution)
         pdf.setFullPage(True)
         pdf.setPrintRange(QPrinter.AllPages)
         pdf.setOutputFileName(self.getName(element))
         pdf.setOutputFormat(QPrinter.PdfFormat)
         element.webFrame().print(pdf)
Exemplo n.º 4
0
    def initTestPageWebView(self):
        
        widget = QWidget()
        
        self.testPageWebView = TestPageWebView()
        refreshButton = QPushButton("Refresh")
        pdfButton = QPushButton("Save PDF")

        buttons = QWidget()
        h2 = QHBoxLayout()
        h2.addWidget(pdfButton)        
        h2.addWidget(refreshButton)     
        h2.setSizeConstraint(QLayout.SetFixedSize)
        buttons.setLayout(h2)        

        v1 = QVBoxLayout()
        v1.addWidget(self.testPageWebView)        
        v1.addWidget(buttons)     
        widget.setLayout(v1)
        
        self.testPageWebView.init()
        
        def setitem(testobj):
            # set testfolder item
            self.tester.setitem(testobj)
            
            # set
            if testobj:
                testhtml, testurl, testhtmlpath = self.tester.getinfopanelhtml(testobj)
                
                if testhtmlpath:
                    self._testhtmlpathpdf = testhtmlpath.with_suffix(".pdf")
                    self.printer.setOutputFileName(str(self._testhtmlpathpdf))
                    
                testqurl = QUrl("file://{}/".format(testurl.resolve()))
                self.testPageWebView.setHtml(testhtml, testqurl)
                    
                
            else:
                self.testPageWebView.setHtml("<html></html>", QUrl())
        
        # Connect Buttons
        self.testitemchanged.connect(lambda obj: setitem(obj) )
        refreshButton.clicked.connect(lambda obj: setitem(self.__current_item) )
        
        ## Save PDF Button
        self.printer = QPrinter()
        self.printer.setPageSize(QPrinter.A4)
        self.printer.setOutputFormat(QPrinter.PdfFormat)
 
        def savePdf():
            self.testPageWebView.print_(self.printer)
            
            msg = "PDF Saved: "+str(self._testhtmlpathpdf)
            print(msg)
            QMessageBox.information(self,"Information",msg)        
        
        pdfButton.clicked.connect(savePdf)
        
        return widget
Exemplo n.º 5
0
    def on_click(self, event):
        #print(self.editor.toPlainText())
        #print(self.editor.toHtml())

        # https://doc.qt.io/qt-5/qtextdocumentwriter.html
        #writer = QtGui.QTextDocumentWriter('output.odf')
        writer = QtGui.QTextDocumentWriter()

        for item in writer.supportedDocumentFormats():
            print('format:', bytes(item).decode())

        doc = self.editor.document()

        writer.setFormat(b'ODF') # has to be bytes, not string
        writer.setFileName('output.odf')
        writer.write(doc)

        writer.setFormat(b'HTML') # has to be bytes, not string
        writer.setFileName('output.html')
        writer.write(doc)
        
        writer.setFormat(b'plaintext') # has to be bytes, not string
        writer.setFileName('output.txt')
        writer.write(doc)

        printer = QPrinter()
        printer.setOutputFormat(QPrinter.PdfFormat)
        printer.setPaperSize(QPrinter.A4);
        printer.setOutputFileName('output.pdf')
        #doc.setPageSize(printer.pageRect().size()) # need QSizeF instead of QSize
        doc.print(printer)
Exemplo n.º 6
0
def PdfConverter(username):

        htmllink = "bootstrap_mod/usertemp/"+username+".html"
        app1 = QApplication(sys.argv)

        web = QWebView()

        link =QUrl.fromLocalFile(QFileInfo(htmllink).absoluteFilePath())

        web.load(QUrl(link))

        printer = QPrinter()
        printer.setPageSize(QPrinter.A4)
        printer.setOutputFormat(QPrinter.PdfFormat)
        Pdf_Generated_Name="bootstrap_mod/usertemp/"+username+".pdf"
        printer.setOutputFileName(Pdf_Generated_Name)

        web.print(printer)
        QApplication.exit()
        def convertIt():
                web.print(printer)
                print("Pdf generated")
                QApplication.exit()

        web.loadFinished.connect(convertIt)
        sys.exit(app1.exec_())
        return 0
Exemplo n.º 7
0
    def exportToPDF(self, path=None):
        if path is None:
            desktop = QStandardPaths.standardLocations(
                QStandardPaths.DesktopLocation)
            path = os.path.join(desktop[0], "metricsWindow.pdf")

        printer = QPrinter()
        # printer.setFullPage(True)
        printer.setOutputFileName(path)
        printer.setOutputFormat(QPrinter.PdfFormat)

        painter = QPainter()
        painter.begin(printer)
        painter.setRenderHint(QPainter.Antialiasing)
        if self._rightToLeft:
            self.paintRightToLeft(painter, self.geometry())
        else:
            self.paintLeftToRight(painter, self.geometry())
        painter.end()
Exemplo n.º 8
0
	def standardPrinter(self, title):
		printer = QPrinter(QPrinter.HighResolution)
		printer.setDocName(title)
		printer.setCreator('ReText %s' % app_version)
		if globalSettings.paperSize:
			pageSize = self.getPageSizeByName(globalSettings.paperSize)
			if pageSize is not None:
				printer.setPaperSize(pageSize)
			else:
				QMessageBox.warning(self, '',
					self.tr('Unrecognized paperSize setting "%s".') %
					globalSettings.paperSize)
		return printer
Exemplo n.º 9
0
    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()
Exemplo n.º 10
0
    def __init__(self, page_size, print_pdf=False):

        super().__init__(page_size)

        self._printer = QPrinter(QPrinter.HighResolution)
        self._printer.setPageSize(QtGui.QPageSize(QtCore.QSizeF(*page_size),
                                                  QtGui.QPageSize.Millimeter))
        self._printer.setColorMode(QPrinter.Color)

        logging.info('Using printer "%s"', self._printer.printerName())

        self._print_pdf = print_pdf
        if self._print_pdf:
            logging.info('Using PDF printer')
            self._counter = 0
            self._printer.setOutputFormat(QPrinter.PdfFormat)
            self._printer.setFullPage(True)
Exemplo n.º 11
0
    def __init__(self, parent=None, html=None):
        super(PrintHtml, self).__init__(parent)

        # html = codecs.open(b"template.html", encoding='utf-8').read()
        baseurl = QUrl.fromLocalFile(os.getcwd() + "/temp/index.html")
        self.setHtml(html, baseurl)
        self.printer = QPrinter()
        self.printer.setPageSize(QPrinter.A4)
        self.printer.setOrientation(QPrinter.Portrait)
        self.printer.setPageMargins(5, 5, 5, 5, QPrinter.Millimeter)
        self.setFixedWidth(1000)

        dialog = QPrintPreviewDialog(self.printer)
        dialog.setWindowState(Qt.WindowMaximized)
        dialog.paintRequested.connect(self.print_)
        dialog.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowMinMaxButtonsHint | Qt.WindowCloseButtonHint | Qt.WindowContextHelpButtonHint)
        dialog.exec()
Exemplo n.º 12
0
    def printing(printer, context):
        p = QPrinter()
        doc = QTextDocument()

        htmlStr = context
        print('aaaa', htmlStr)
        doc.setHtml(htmlStr)
        doc.setPageSize(
            QSizeF(p.logicalDpiX() * (80 / 25.4),
                   p.logicalDpiY() * (297 / 25.4)))
        p.setOutputFormat(QPrinter.NativeFormat)
        doc.print_(p)
Exemplo n.º 13
0
 def printing_22(printer, context):
     printerInfo = QPrinterInfo()
     p = QPrinter()
     for item in printerInfo.availablePrinters():
         if printer == str(item.printerName()):
             p = QPrinter(item)
             doc = QTextDocument()
             font = doc.defaultFont()
             font.setBold(True)
             font.setPointSize(font.pointSize() + 1)
             doc.setDefaultFont(font)
             font.setPixelSize(5)
             # doc.setPageSize(QSizeF(p.logicalDpiX() * (88 / 25.4),
             #                        p.logicalDpiY() * (297 / 25.4)))
             # x是间距,数字越小间距越大 y是纵长度 越大长度越小
             doc.setPageSize(QSizeF(p.logicalDpiX() * (60 / 25.4), p.logicalDpiY() * (3500 / 25.4)))
             p.setOutputFormat(QPrinter.NativeFormat)
             doc.setHtml(u'%s' % context)
             doc.print_(p)
Exemplo n.º 14
0
    def filePrintPdf(self):
        fn, _ = QFileDialog.getSaveFileName(
            self, "Export PDF", None, "PDF files (*.pdf);;All Files (*)")

        if fn:
            if QFileInfo(fn).suffix().isEmpty():
                fn += '.pdf'

            printer = QPrinter(QPrinter.HighResolution)
            printer.setOutputFormat(QPrinter.PdfFormat)
            printer.setOutputFileName(fn)
            self.textEdit.document().print_(printer)
Exemplo n.º 15
0
 def pdf(self):
     self.filename = QFileDialog.getSaveFileName(self,
                                                 self.tr("Export document to PDF"),
                                                 "", self.tr("PDF files (*.pdf)"))[0]
     if self.filename:
         # Append extension if not there yet
         if not self.filename.endswith(".pdf"):
             self.filename += ".pdf"
         printer = QPrinter()
         printer.setOutputFormat(QPrinter.PdfFormat)
         printer.setOutputFileName(self.filename)
         self.outputText.document().print(printer)
Exemplo n.º 16
0
    def Conversion_en_pdf(self):

        fn, _ = QFileDialog.getSaveFileName(self, "exporter en pdf", None,
                                            "PDF files (.pdf)")
        if fn != '':
            if QFileInfo(fn).suffix() == "":
                fn += '.pdf'

            imprimeur = QPrinter(QPrinter.HighResolution)
            imprimeur.setOutputFormat(QPrinter.PdfFormat)
            imprimeur.setOutputFileName(fn)
            self.fen1.textEdit.document().print_(imprimeur)
Exemplo n.º 17
0
    def __init__(self):
        super(MyWindow, self).__init__()
        self.initGUI("PyQt5 学习 PrintDialog Printer")

        # NOTE: 注意这里要先获得一个打印机
        self.printer = QPrinter()

        mainLayout = QGridLayout()
        self.setLayout(mainLayout)

        scrollarea = QScrollArea(self)
        self.textedit = QTextEdit(self)
        self.textedit.setText("请在这里输入文字")
        self.textedit.setAlignment(Qt.AlignLeading)
        scrollarea.setWidget(self.textedit)
        scrollarea.setWidgetResizable(True)
        scrollarea.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        scrollarea.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        mainLayout.addWidget(scrollarea, 0, 0, 3, 1)

        vbox = QVBoxLayout()
        self.btn_openOneFile = QPushButton("选择文本文件")
        self.btn_openMultipleFile = QPushButton("打开多个文件")
        self.btn_saveFile = QPushButton("保存文件")
        self.btn_color = QPushButton("选择颜色")
        self.btn_font = QPushButton("选择字体")
        self.btn_pagesetting = QPushButton("页面设置")
        self.btn_printdialog = QPushButton("打印文档")
        vbox.addWidget(self.btn_openOneFile)
        vbox.addWidget(self.btn_openMultipleFile)
        vbox.addWidget(self.btn_saveFile)
        vbox.addWidget(self.btn_color)
        vbox.addWidget(self.btn_font)
        vbox.addWidget(self.btn_pagesetting)
        vbox.addWidget(self.btn_printdialog)
        mainLayout.addLayout(vbox, 0, 1, 3, 1)

        # 为按钮绑定槽函数
        self.btn_openOneFile.clicked.connect(self.on_btn_clicked)
        self.btn_openMultipleFile.clicked.connect(self.on_btn_clicked)
        self.btn_saveFile.clicked.connect(self.on_btn_clicked)
        self.btn_color.clicked.connect(self.on_btn_clicked)
        self.btn_font.clicked.connect(self.on_btn_clicked)
        self.btn_pagesetting.clicked.connect(self.on_btn_clicked)
        self.btn_printdialog.clicked.connect(self.on_btn_clicked)
Exemplo n.º 18
0
    def __init__(self):
        self.path_work, self.res_path = '', ''
        self.obj_an, self.fileName = '', ''
        self.levi, self.ny = 0, 0
        self.type_an = 'fast'
        self.model_name = 'Model_1_85aug.h5'
        self.monte_c = 5
        self.numx_start, self.numx_stop, self.list_proc, self.start_i, self.stop_i = [], [], [], [], []
        self.lev_sec = 1
        user32 = ctypes.windll.user32
        self.screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)

        super(ImageViewer, self).__init__()

        self.printer = QPrinter()
        self.scaleFactor = 0.0
        self.imageLabel = QLabel("Steps to start the analysis:\n \n"
                                 "1) File         ---> Select svs or select the yellow folder in the toolbar\n\n"
                                 "2) Analysis ---> Stat analysis or select the green arrow in the toolbar ")

        self.imageLabel.setFont(QFont("Helvetica", 15, QFont.Black))
        self.setCentralWidget(self.imageLabel)

        self.imageLabel.setBackgroundRole(QPalette.Dark)
        self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.imageLabel.setScaledContents(True)

        self.scrollArea = QScrollArea()
        self.scrollArea.setBackgroundRole(QPalette.Dark)
        self.scrollArea.setWidget(self.imageLabel)
        self.setCentralWidget(self.scrollArea)
        self.scrollArea.setAlignment(Qt.AlignCenter)

        self.threadPool = QThreadPool()

        self.toolbar = QToolBar("My main toolbar")
        self.addToolBar(self.toolbar)
        self.toolbar.setStyleSheet("QToolBar{spacing:15px;}")

        self.createActions()
        self.createMenus()

        self.setWindowTitle("Bayesian Analayzer")
        self.setWindowIcon(QIcon('icons/target.ico'))
        self.showMaximized()
Exemplo n.º 19
0
def printMessageTE(textEd):
    """ Print qtextedit or global widget,
        Uses QPrintDialog
    """

    debug = False
    if debug:
        print("  -- in printLog")

    printer = QPrinter()

    printer.Letter
    printer.HighResolution
    printer.Color

    anotherWidget = QPrintDialog(printer)
    if (anotherWidget.exec_() == QDialog.Accepted):
        textEd.document().print_(anotherWidget.printer())
Exemplo n.º 20
0
    def printPreview(self):
        #* Generate PDF in path
        currentdir = os.path.dirname(os.path.realpath(__file__))
        html_path = os.path.join(currentdir, "index.html")
        pdf_path = os.path.join(currentdir, "index.pdf")
        converter = HyperPDFizer(html_path, pdf_path, currentdir)
        converter.run()

        if self.page is None:
            return
        if self.m_inPrintPreview:
            return
        self.m_inPrintPreview = True
        printer = QPrinter()
        preview = QPrintPreviewDialog(printer, self.page.view())
        preview.paintRequested.connect(self.printDocument)
        preview.exec_()
        self.m_inPrintPreview = False
Exemplo n.º 21
0
 def createPrinteDialog(self,bill):
     try:
         printer = QPrinter(QPrinter.ScreenResolution)
         printer.setPageSize(30)
         printer.setFullPage(True)
         painter = QPainter()
         painter.begin(printer)
         painter.setFont(QFont("Segoe UI", 10, 1500))
         painter.drawText(230, 30, 0, 2000,Qt.TextIncludeTrailingSpaces | Qt.AlignRight, bill)
         painter.end()
         # print(bill)
     except Exception as e:
         print(e)
Exemplo n.º 22
0
    def print_sheet(self):
        printer = QPrinter(QPrinterInfo.defaultPrinter())
        printer.setOutputFileName('foo.pdf')
        printer.setResolution(72)
        printer.setFullPage(True)

        self.webRptView.print(printer)

        pdf = 'foo.pdf'
            
        AcroRD32Path = winreg.QueryValue(winreg.HKEY_CLASSES_ROOT, 'Software\\Adobe\\Acrobat\Exe')
            
        acroread = AcroRD32Path
            
        cmd= '{0} /N /T "{1}" ""'.format(acroread,pdf)  
        proc = subprocess.Popen(cmd)
        time.sleep(5)
           
        os.system('TASKKILL /F /IM AcroRD32.exe')
        os.remove('foo.pdf')   
Exemplo n.º 23
0
 def printPDF(self):
     """
     ---------------------------------------------
     Export diagram as pdf onto specified folder
     fn = user input directory
     ---------------------------------------------
     """
     fn, _ = QFileDialog.getSaveFileName(self, "Export PDF", None,
                                         "PDF files (.pdf);;All Files()")
     if fn != "":
         if QFileInfo(fn).suffix() == "":
             fn += ".pdf"
         printer = QPrinter(QPrinter.HighResolution)
         printer.setOrientation(QPrinter.Landscape)
         printer.setOutputFormat(QPrinter.PdfFormat)
         printer.setOutputFileName(fn)
         painter = QPainter(printer)
         self.diagramScene.render(painter)
         painter.end()
         self.logger.info("File exported to %s" % fn)
Exemplo n.º 24
0
 def topo_show(self, ListA: list, ListB: list, ListC: list):
     sip.delete(self.graphicsView.scene)
     # self.graphicsView.scene = QtWidgets.QGraphicsScene(0, 0, 800, 600)
     self.graphicsView.scene = QtWidgets.QGraphicsScene(0, 0, 1500, 1000)
     self.graphicsView.setScene(self.graphicsView.scene)
     self.graphicsView.setAlignment(QtCore.Qt.AlignHCenter
                                    | QtCore.Qt.AlignVCenter)
     # self.graphicsView.setSceneRect(0, 0, 1600, 1200)  # fix scene size 500 500
     self.graphicsView.setSceneRect(0, 0, 3000,
                                    1800)  # fix scene size 500 500
     self.graphicsView.setRenderHint(QPainter.Antialiasing)  ##设置视图的抗锯齿渲染模式。
     self.scene = QGraphicsScene()
     self.graphicsView.setScene(self.scene)
     root_nodeA = self.getRoot(ListA)
     root_nodeB = self.getRoot(ListB).getFirstChild()
     root_nodeC = self.getRoot(ListC).getFirstChild()
     color_A = QPen(Qt.green)
     ymax_A = self.single_topo(ListA, 0, 0, 0, root_nodeA, color_A)
     yby = ymax_A - 80
     color_B = QPen(Qt.darkCyan)
     ymax_B = self.single_topo(ListB, 10, yby, ymax_A, root_nodeB, color_B)
     ycy = ymax_B - 80
     color_C = QPen(Qt.cyan)
     self.single_topo(ListC, 20, ycy, ymax_B, root_nodeC, color_C)
     self.graphicsView.centerOn(0, 00)
     printer_pixmap = QPrinter(QPrinter.HighResolution)
     printer_pixmap.setPageSize(QPrinter.A4)
     printer_pixmap.setOutputFormat(QPrinter.PdfFormat)
     time_str = datetime.datetime.now().strftime('%Y%m%d-%H_%M_%S')
     pngname = '../backup/topo/' + time_str + '.pdf'
     printer_pixmap.setOutputFileName(pngname)
     outputimg = QPixmap(3840, 1160)
     outputimg.fill(Qt.white)
     self.graphicsView.viewport().render(outputimg)
     painter_pixmap = QPainter()
     painter_pixmap.begin(printer_pixmap)
     rect = painter_pixmap.viewport()
     multiple = 3 * rect.width() / outputimg.width()
     painter_pixmap.scale(multiple, multiple)
     painter_pixmap.drawPixmap(0, 0, outputimg)
     painter_pixmap.end()
Exemplo n.º 25
0
def print_file(fileName, printFunction):
    """This method print a file

    This method print a file, fileName is the default fileName,
    and printFunction is a funcion that takes a QPrinter
    object and print the file,
    the print method
    More info on:http://doc.qt.nokia.com/latest/printing.html"""

    printer = QPrinter(QPrinter.HighResolution)
    printer.setPageSize(QPrinter.A4)
    printer.setOutputFileName(fileName)
    printer.setDocName(fileName)

    preview = QPrintPreviewDialog(printer)
    preview.paintRequested[QPrinter].connect(printFunction)
    size = QApplication.instance().desktop().screenGeometry()
    width = size.width() - 100
    height = size.height() - 100
    preview.setMinimumSize(width, height)
    preview.exec_()
Exemplo n.º 26
0
    def vistaPrevia(self):
        if not self.documento.isEmpty():
            impresion = QPrinter(QPrinter.HighResolution)

            vista = QPrintPreviewDialog(impresion, self)
            vista.setWindowTitle("Vista previa")
            vista.setWindowFlags(Qt.Window)
            vista.resize(800, 600)

            exportarPDF = vista.findChildren(QToolBar)
            exportarPDF[0].addAction(QIcon("exportarPDF.png"),
                                     "Exportar a PDF", self.exportarPDF)

            vista.paintRequested.connect(self.vistaPreviaImpresion)
            vista.exec_()
        else:
            QMessageBox.critical(self, "Vista previa",
                                 "No hay datos para visualizar.   ",
                                 QMessageBox.Ok)
    def initUI(self):
        self.setGeometry(300, 300, 500, 300)
        self.setWindowTitle('颜色字体文件')

        self.text = QTextEdit(self)
        self.text.setGeometry(20, 20, 300, 270)

        self.bt1 = QPushButton('打开文件', self)
        self.bt1.move(350, 20)

        self.bt2 = QPushButton('打开多个文件', self)
        self.bt2.move(350, 50)

        self.bt3 = QPushButton('选择字体', self)
        self.bt3.move(350, 80)

        self.bt4 = QPushButton('选择颜色', self)
        self.bt4.move(350, 110)

        self.bt5 = QPushButton('保存文件', self)
        self.bt5.move(350, 140)

        self.bt8 = QPushButton('另存为', self)
        self.bt8.move(350, 170)

        self.bt6 = QPushButton('页面设置', self)
        self.bt6.move(350, 200)

        self.bt7 = QPushButton('打印文档', self)
        self.bt7.move(350, 230)

        self.bt1.clicked.connect(self.fileopen)
        self.bt2.clicked.connect(self.filesopen)
        self.bt3.clicked.connect(self.choicefont)
        self.bt4.clicked.connect(self.choicecolor)
        self.bt5.clicked.connect(self.fileopen)
        self.bt6.clicked.connect(self.pagesetting)
        self.bt7.clicked.connect(self.printdialog)
        self.bt8.clicked.connect(self.filesave)

        self.printer = QPrinter()

        self.show()
    def __init__(self):
        super(MeetingTableView, self).__init__()
        self.resize(1000, 530)
        self.setWindowTitle("Audit information statistics platform")

        self.queryModel = None

        self.tableView = None

        self.currentPage = 0

        self.totalPage = 0

        self.totalRecord = 0

        self.pageRecord = 15
        self.printer = QPrinter()
        self.editor = QtWidgets.QTextEdit(self)
        self.editor.hide()
        self.setUpUI()
Exemplo n.º 29
0
def html_to_image(StrPrintHtml="", printer_name="", widthPage=300, heightPage=100, leftPage=-15, topPage=-15 , filename=""):
    """
    Функция вывода текста на принтер
    :param StrPrintHtml: - Текст HTML
    :param printer_name: - имя принтера
    :return:
    """
    requestMessage = {}
    requestMessage["WidthPage"] = widthPage
    requestMessage["HeightPage"] = heightPage
    requestMessage["LeftPage"] = leftPage
    requestMessage["TopPage"] = topPage
    requestMessage["filename"] = filename
    requestMessage["status"] = 0
    try:
        app = QApplication([])
        printer = QPrinter()
        label = QLabel()
        # '<img width="300"  height="100"  alt="" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAALQAAAB2CAIAAADujy7aAAABuUlEQVR42u3YwY7CIBRAUZj4/7/MLEgIFlqf1YwOPWdlsKlVrlDNqVNKSSnlnNvjqo6MR47PjuP9OSNniJw/foWRa4tc7d45n32tyDvtRyLjkWuIfErjGX4S7BAH4kAciANxIA7EgTgQB+JAHCAOxIE4EAfiQByIA3EgDsQB4kAciANxIA7EgTgQB+JAHCAOxIE4EAfiQByIA3EgDsSBOEAciANxIA7EgTgQB+JAHIgDxIE4EAfiQByIA3EgDsSBOEAciANxIA7EgTgQB+JAHIgDcYA4EAfiQByIA3EgDsSBOBAHiANxIA7EgTgQB+JAHIgDcYA4EAfiQByIg0/LpRSfAlYOxMGb3FbbJvPdRplzbo/b+CuD/Ugbnw6K4+vKOA6lTuQrg5tZr684HbStfO+a8alX/PvLEMdjwSmZHtZvDW12T8zxSmVc6IZ0utT3c1n72JvdcXw6stKesuAN6d56ML1tnE726W9/fxvrhvR/7zX9FI5LyHgruvD2ccVt5WCpiM9u5MiVtpKL3nOcWPaX/z3y4O0v8z43X9/Nf1bT/7WmR6bD/7sOinn2d5M4sK0gDsQB4uDQLyTS/Ojjiz5LAAAAAElFTkSuQmCC" />'
        label.setText(StrPrintHtml)
        label.resize(int(widthPage), int(heightPage))
        if printer_name == "":
            printer_name = GetDefaultPrinter()
        requestMessage["PrinterName"] = printer_name
        printer.setPrinterName(printer_name)
        # для отладки
        if filename != "":
            # printer.setPrinterName("Brother QL-810W")
            printer.setOutputFileName(filename)
        printer.setPageMargins(0, 0, 0, 0, QPrinter.DevicePixel)
        painter = QPainter()
        painter.begin(printer)
        painter.drawPixmap(int(leftPage),int(topPage), label.grab())
        painter.end()
    except Exception:
        requestMessage["Error"] = "%s" % (format_exc())
        return requestMessage
    requestMessage["status"] = 1
    return requestMessage
Exemplo n.º 30
0
    def slotPrint(self):
        #实例化打印图像对象
        printer=QPrinter()
        #打印窗口弹出
        printDialog=QPrintDialog(printer,self)
        if printDialog.exec_():

            painter=QPainter(printer)
            #实例化视图窗口
            rect=painter.viewport()
            #获取图片的尺寸
            size=self.image.size()

            size.scale(rect.size(),Qt.KeepAspectRatio)
            #设置视图窗口的属性
            painter.setViewport(rect.x(),rect.y(),size.width(),size.height())

            #设置窗口的大小为图片的尺寸,并在窗口内绘制图片
            painter.setWindow(self.image.rect)
            painter.drawImage(0,0,self.image)
    def __init__(self):
        super(InstructTableView, self).__init__()
        self.resize(1000, 715)
        self.setWindowTitle("Rectification opinion statistics system")

        self.queryModel = None

        self.tableView = None

        self.currentPage = 0

        self.totalPage = 0

        self.totalRecord = 0

        self.pageRecord = 15
        self.printer = QPrinter()
        self.editor = QtWidgets.QTextEdit(self)
        self.editor.hide()
        self.setUpUI()
Exemplo n.º 32
0
    def exportPdf(self):
        if self.textEdit.toPlainText() == '':
            QMessageBox.critical(self, "No text",
                                 "Please type something then export to pdf")
            return
        fn, _ = QFileDialog.getSaveFileName(
            self, "Export PDF", None, "PDF files (*.pdf) ;; All files (*.*)")
        if fn != "":
            if QFileInfo(fn).suffix() == "":
                fn += '.pdf'

            printer = QPrinter(QPrinter.HighResolution)
            printer.setOutputFormat(QPrinter.PdfFormat)
            printer.setOutputFileName(fn)
            self.textEdit.document().print(printer)
Exemplo n.º 33
0
 def createPrinteDialog(self):
     try:
         bill = ""
         for i in range(len(dig.bill)):
             bill += dig.bill.item(i).text() + "\n"
         printer = QPrinter(QPrinter.ScreenResolution)
         printer.setPageSize(30)
         printer.setFullPage(True)
         painter = QPainter()
         painter.begin(printer)
         painter.setFont(QFont("Segoe UI", 10, 1500))
         painter.drawText(230, 0, 0, 2000, Qt.TextIncludeTrailingSpaces | Qt.AlignRight, bill)
         painter.end()
     except Exception as e:
         print(e)
Exemplo n.º 34
0
    def __init__(self):
        super(ImageViewer, self).__init__()

        self.printer = QPrinter()
        self.scaleFactor = 0.0

        self.imageLabel = QLabel()
        self.imageLabel.setBackgroundRole(QPalette.Base)
        self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.imageLabel.setScaledContents(True)

        self.scrollArea = QScrollArea()
        self.scrollArea.setBackgroundRole(QPalette.Dark)
        self.scrollArea.setWidget(self.imageLabel)
        self.setCentralWidget(self.scrollArea)

        self.createActions()
        self.createMenus()

        self.setWindowTitle("Image Viewer")
        self.resize(500, 400)
Exemplo n.º 35
0
    def view(self):
    #Vista previa

        if not self.document.isEmpty():

            impres = QPrinter(QPrinter.HighResolution)
                
            var_view = QPrintPreviewDialog(impres, self)
            var_view.setWindowTitle("Vista previa")
            var_view.setWindowFlags(Qt.Window)
            var_view.resize(800, 600)

            exportarPDF = var_view.findChildren(QToolBar)
            exportarPDF[0].addAction(QIcon("logo.png"), "Exportar a PDF", self.pdf_export)
                
            var_view.paintRequested.connect(self.visualizar) 
            var_view.exec_()
        
        else:
            QMessageBox.critical(self, "Atención", "No hay datos en la tabla ",
                                 QMessageBox.Ok)
Exemplo n.º 36
0
    def checkPageLayout(self):
        """Check and set the page layout on the current printer.

        Verify that the layout settings match the printer, adjust if required.
        """
        if not self.printer.setPageLayout(self.pageLayout):
            tempPrinter = QPrinter()
            tempPageLayout = tempPrinter.pageLayout()
            tempPageLayout.setUnits(QPageLayout.Inch)
            pageSizeIssue = False
            defaultPageSize = tempPageLayout.pageSize()
            tempPageLayout.setPageSize(self.pageLayout.pageSize())
            if not tempPrinter.setPageLayout(tempPageLayout):
                pageSizeIssue = True
                tempPageLayout.setPageSize(defaultPageSize)
            marginIssue = not (tempPageLayout.setMargins(
                self.pageLayout.margins())
                               and tempPrinter.setPageLayout(tempPageLayout))
            if marginIssue:
                margin = 0.1
                while True:
                    if (tempPageLayout.setMargins(QMarginsF(*(margin, ) * 4))
                            and tempPrinter.setPageLayout(tempPageLayout)):
                        break
                    margin += 0.1
                newMargins = []
                for oldMargin in self.roundedMargins():
                    newMargins.append(
                        oldMargin if oldMargin >= margin else margin)
                tempPageLayout.setMargins(QMarginsF(*newMargins))
            tempPageLayout.setOrientation(self.pageLayout.orientation())
            self.printer.setPageLayout(tempPageLayout)
            if not pageSizeIssue and not marginIssue:
                return
            if pageSizeIssue and marginIssue:
                msg = _('Warning: Page size and margin settings unsupported '
                        'on current printer.\nSave page adjustments?')
            elif pageSizeIssue:
                msg = _('Warning: Page size setting unsupported '
                        'on current printer.\nSave adjustment?')
            else:
                msg = _('Warning: Margin settings unsupported '
                        'on current printer.\nSave adjustments?')
            ans = QMessageBox.warning(QApplication.activeWindow(), 'TreeLine',
                                      msg, QMessageBox.Yes | QMessageBox.No,
                                      QMessageBox.Yes)
            if ans == QMessageBox.Yes:
                self.pageLayout = tempPageLayout
Exemplo n.º 37
0
    def __init__(self):
        super().__init__()

        self.printer = QPrinter()
        self.scaleFactor = 0.0
        self.selected_page = 0
        self.selected_document = ""

        self.createToolbar()
        self.createActions()
        self.createMenus()
        #self.createProgressBar()
        
        # statub Bar
        self.statusBar().showMessage("Ready")
        # self.setStatusBar(QStatusBar(self))      

        self.createLeftGroupBox()
        self.createRightGroupBox()
        
        #self.createProgressBar()

        self.mainLayout = QGridLayout()
        self.mainLayout.addWidget(self.topLeftGroupBox, 1, 0)
        self.mainLayout.addWidget(self.RightGroupBox, 1, 1)
        
        #mainLayout.addWidget(self.progressBar, 3, 0, 1, 2)
        
        self.mainLayout.setColumnStretch(0, 1)
        self.mainLayout.setColumnStretch(1, 1)

        wid = QtWidgets.QWidget(self)
        self.setCentralWidget(wid)
        wid.setLayout(self.mainLayout)

        self.setWindowTitle("Jabil DHR Document Inspector 1.0")
        self.showMaximized()
        #self.resize(1280, 680)

        self.load_video_feed()
Exemplo n.º 38
0
def generate_pdf(template, filename, media_path=None, template_context=None):
    global app

    if template_context is None:
        template_context = {}
    template_context['media_path'] = media_path
    #put your templates in the pdf subdirectory
    template_path = '{0}.html'.format(template)
    template = jinja_env.get_template(template_path)
    html = template.render(**template_context)
    app = QApplication.instance()
    if app is None:
        app = QApplication(['--platform', 'minimal'])
    web = QWebView()
    url = QUrl.fromLocalFile(media_path)
    web.setHtml(html, baseUrl=url)
    #we need this call to correctly render images...
    app.processEvents()
    printer = QPrinter()
    printer.setPageSize(QPrinter.A4)
    printer.setOutputFormat(QPrinter.PdfFormat)
    printer.setOutputFileName(filename)
    web.print_(printer)
Exemplo n.º 39
0
    def PENT(self):
        Namee = self.ui.rqm.text()
        conn = sqlite3.connect('ALLCOM.db')
        c = conn.cursor()
        try:
            SQLl = c.execute("SELECT sum(commision) FROM COMM WHERE unit like ?", (Namee,))
            for i in SQLl:
                print(i)

            #   conn.commit()
            # for row in SQLl:
            # print(str(row[5]))
            # t1 = row[5] * -1
            self.ui.VIEW.append("إجمالي ايرادات المندوب:" + Namee + str(i) + " ريال سعودي")
            self.ui.VIEW.append("the total commision of sals rep is: ".title() + str(i) + " sar" + Namee)
        except Exception as eee:
            print(eee)
        c.close()
        printer = QPrinter(QPrinter.HighResolution)
        previewDialog = QPrintPreviewDialog(printer, self)
        previewDialog.paintRequested.connect(self.printPreview)
        previewDialog.exec_()
Exemplo n.º 40
0
def process_html(htmlpath, args, app):

    htmlurl = urllib.parse.quote(htmlpath.resolve().absolute().as_posix())
    htmlQurl = QUrl("file://{}".format(htmlurl))

    pdfOutputPath = htmlpath.with_suffix(".pdf")

    print("htmlpath:", htmlpath)
    print("htmlurl:", htmlurl)
    print("htmlQurl:", htmlQurl)
    print("pdfOutputPath:", pdfOutputPath)

    web = QWebView()
    web.page().settings().setAttribute(QWebSettings.DeveloperExtrasEnabled,
                                       True)

    printer = QPrinter()
    printer.setPageSize(QPrinter.A4)
    printer.setOutputFormat(QPrinter.PdfFormat)
    printer.setOutputFileName(str(pdfOutputPath))

    def convertIt():
        web.print_(printer)
        print("Pdf generated")

    def closeIt():
        QApplication.exit()

    web.loadFinished.connect(convertIt)

    if args.show:
        web.show()
    else:
        web.loadFinished.connect(closeIt)

    web.load(htmlQurl)
Exemplo n.º 41
0
    def exportarPDF(self):
        if not self.documento.isEmpty():
            nombreArchivo, _ = QFileDialog.getSaveFileName(self, "Экспорт в PDF", "Список пользователей ",
                                                           "PDF файлы  (*.doc);;All Files (*)",
                                                           options=QFileDialog.Options())

            if nombreArchivo:
                impresion = QPrinter(QPrinter.HighResolution)
                impresion.setOutputFormat(QPrinter.PdfFormat)
                impresion.setOutputFileName(nombreArchivo)
                self.documento.print_(impresion)

                QMessageBox.information(self, "Экспорт в PDF", "Данные успешно экспортированы.   ",
                                        QMessageBox.Ok)
        else:
            QMessageBox.critical(self, "Экспорт в PDF", "Нет данных для экспорта.   ",
                                 QMessageBox.Ok)
Exemplo n.º 42
0
def print_file(fileName, printFunction):
    """This method print a file

    This method print a file, fileName is the default fileName,
    and printFunction is a funcion that takes a QPrinter
    object and print the file,
    the print method
    More info on:http://doc.qt.nokia.com/latest/printing.html"""

    printer = QPrinter(QPrinter.HighResolution)
    printer.setPageSize(QPrinter.A4)
    printer.setOutputFileName(fileName)
    printer.setDocName(fileName)

    preview = QPrintPreviewDialog(printer)
    preview.paintRequested['QPrinter*'].connect(printFunction)
    size = QApplication.instance().desktop().screenGeometry()
    width = size.width() - 100
    height = size.height() - 100
    preview.setMinimumSize(width, height)
    preview.exec_()
Exemplo n.º 43
0
def process_html(htmlpath, args, app):
    
    
    htmlurl = urllib.parse.quote(htmlpath.resolve().absolute().as_posix())
    htmlQurl = QUrl("file://{}".format(htmlurl))
 
    pdfOutputPath = htmlpath.with_suffix(".pdf")
    
    print("htmlpath:", htmlpath)
    print("htmlurl:", htmlurl)
    print("htmlQurl:", htmlQurl)
    print("pdfOutputPath:", pdfOutputPath)
    
    web = QWebView()
    web.page().settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
    
    printer = QPrinter()
    printer.setPageSize(QPrinter.A4)
    printer.setOutputFormat(QPrinter.PdfFormat)
    printer.setOutputFileName(str(pdfOutputPath))
 
    def convertIt():
        web.print_(printer)
        print("Pdf generated")
    
    def closeIt():
        QApplication.exit()
 
    web.loadFinished.connect(convertIt)

    if args.show:
        web.show()
    else:
        web.loadFinished.connect(closeIt)
    
    web.load(htmlQurl)
Exemplo n.º 44
0
    def toPdf(self, image, n=0):
        printer = QPrinter()
        printer.setPaperSize(QSizeF(210, 297), QPrinter.Millimeter);
        printer.setResolution(600)
        printer.setPageMargins(0,0,0,0, QPrinter.Millimeter)
        printer.setOutputFormat(QPrinter.PdfFormat)
        printer.setOutputFileName(self.base_name+self.filename+'.pdf')
        printer.setPageMargins(0,0,0,0,6)
        painter = QPainter()
        painter.begin(printer)

        w = int(4958/13)
        h = int(7017/13)
        
        size_h = 2022+int(self.calibration_h) 
        size_v = 1274+int(self.calibration_v)

        image =  image.scaled(size_h, size_v)

        for n in range(3):
            painter.fillRect(0, (n*(7017/3)), 4958, 33, Qt.black )
            painter.fillRect(0, (n*(7017/3))+3, 4958, 27, Qt.white )
            painter.drawImage(553,(n*(7017/3))+533, image)
            wpath = QPainterPath()
            wpath.addRoundedRect(QRectF(548,(n*(7017/3))+528, size_h+5, size_v+5), 19, 19)
            painter.setPen(QPen(Qt.black, 10))
            painter.drawPath(wpath)
        
       
        
        '''
        master public key
        qr_mpk = qrcode.make(self.mpk[0])#
        painter.drawImage(3453,933, ImageQt(qr_mpk))

        painter.setFont(QFont('Din Trek', 18, QFont.Black))
        pen = QPen(Qt.black, 127)
        painter.setPen(pen)

        painter.fillRect(0, 133+(n*(7017/4)), w, 173, Qt.black )
        painter.fillRect(0, 133+(n*(7017/4))+3, w-3, 167, Qt.white )
        painter.drawText(177, 266 + (n*(7017/4)), 'R')
        '''
                                    

        painter.end()
Exemplo n.º 45
0
	def standardPrinter(self):
		printer = QPrinter(QPrinter.HighResolution)
		printer.setDocName(self.currentTab.getDocumentTitle())
		printer.setCreator('ReText %s' % app_version)
		return printer
Exemplo n.º 46
0
 def __printPreviewDiagram(self):
     """
     Private slot called to show a print preview of the diagram.
     """
     from PyQt5.QtPrintSupport import QPrintPreviewDialog
     
     printer = QPrinter(mode=QPrinter.ScreenResolution)
     printer.setFullPage(True)
     if Preferences.getPrinter("ColorMode"):
         printer.setColorMode(QPrinter.Color)
     else:
         printer.setColorMode(QPrinter.GrayScale)
     if Preferences.getPrinter("FirstPageFirst"):
         printer.setPageOrder(QPrinter.FirstPageFirst)
     else:
         printer.setPageOrder(QPrinter.LastPageFirst)
     printer.setPageMargins(
         Preferences.getPrinter("LeftMargin") * 10,
         Preferences.getPrinter("TopMargin") * 10,
         Preferences.getPrinter("RightMargin") * 10,
         Preferences.getPrinter("BottomMargin") * 10,
         QPrinter.Millimeter
     )
     printer.setPrinterName(Preferences.getPrinter("PrinterName"))
     
     preview = QPrintPreviewDialog(printer, self)
     preview.paintRequested[QPrinter].connect(self.__print)
     preview.exec_()
Exemplo n.º 47
0
 def __printDiagram(self):
     """
     Private slot called to print the diagram.
     """
     printer = QPrinter(mode=QPrinter.ScreenResolution)
     printer.setFullPage(True)
     if Preferences.getPrinter("ColorMode"):
         printer.setColorMode(QPrinter.Color)
     else:
         printer.setColorMode(QPrinter.GrayScale)
     if Preferences.getPrinter("FirstPageFirst"):
         printer.setPageOrder(QPrinter.FirstPageFirst)
     else:
         printer.setPageOrder(QPrinter.LastPageFirst)
     printer.setPrinterName(Preferences.getPrinter("PrinterName"))
     
     printDialog = QPrintDialog(printer, self)
     if printDialog.exec_():
         self.__print(printer)
Exemplo n.º 48
0
    def print_webpage(self):
        """Print the webpage to a printer.

        Callback for the print action.
        Should show a print dialog and print the webpage to the printer.
        """
        print_settings = self.config.get("print_settings", {})

        if print_settings.get("mode") == "high":
            printer = QPrinter(mode=QPrinter.HighResolution)
        else:
            printer = QPrinter(mode=QPrinter.ScreenResolution)

        # set which printer
        # FIXME: This isn't documented, because it doesn't seem to work...
        if print_settings.get("printer_name"):
            debug(
                "Setting printer to: {}".format(
                    print_settings.get("printer_name"))
            )
            printer.setPrinterName(print_settings.get("printer_name"))
            debug("Printer is now: {}".format(printer.printerName()))

        # Set the units
        unit_name = print_settings.get("size_unit", 'Millimeter').title()
        try:
            unit = getattr(QPrinter, unit_name)
        except AttributeError:
            debug(
                "Specified print size unit '{}' not found, using default."
                .format(unit_name)
            )
            unit = QPrinter.Millimeter

        # Set the margins
        margins = list(
            print_settings.get("margins", printer.getPageMargins(unit))
        )
        margins.append(unit)
        printer.setPageMargins(*margins)

        # Set the Orientation
        orientation = print_settings.get("orientation", 'Portrait').title()
        printer.setOrientation(
            getattr(QPrinter, orientation, QPrinter.Portrait)
        )

        # Set the paper size
        paper_size = print_settings.get("paper_size")
        if type(paper_size) in (list, tuple):
            # Assume it's a width/height spec
            printer.setPaperSize(QSizeF(*paper_size), unit)
        elif paper_size is not None:  # Assume it's a size name
            printer.setPaperSize(getattr(QPrinter, paper_size, 'AnsiA'))
        # If paper_size is None, we just leave it at the printer's default

        # Set the resolution
        resolution = print_settings.get("resolution")
        if resolution:
            printer.setResolution(int(resolution))

        # Show a print dialog, unless we want silent printing
        if not print_settings.get("silent"):
            print_dialog = QPrintDialog(printer, self)
            print_dialog.setWindowTitle("Print Page")
            if not print_dialog.exec_() == QDialog.Accepted:
                return False

        self.print_(printer)
        return True
Exemplo n.º 49
0
class DataProcessorGuiMain(QMainWindow):

    starttestitemchanged = Signal(object)
    testitemchanged = Signal(object)

    def __init__(self):
        super().__init__()
        self.settings = QSettings("Scilab", "Dataprocessor Gui")
        self.initUI()
        self.__current_item = None

    def infoTestInfoPanel(self):
        
        # == LeftLayout ==
        leftLayout = QVBoxLayout()

        # == TestInfo List ==
        self.testList = ExperTestList(parent=self)
        
        # self.testList.currentItemChanged.connect(lambda c, p: self.testitemchanged.emit(c))
        
        leftLayout.addWidget(self.testList)

        # Sort Combo Box
        def updateSorter(keyText):
            self.testList.setSortKey(keyText)
            self.tester.projectrefresh.emit()
            
        combo = QComboBox(self)
        combo.addItem("–")
        [ combo.addItem(keyerName) for keyerName in sorted(self.testList.sortKeyers.keys()) ]
        combo.activated[str].connect(updateSorter)
        leftLayout.addWidget(combo)
        
        # Refresh Test Lists
        updateButton = QPushButton("Refresh")
        updateButton.clicked.connect(lambda: self.tester.projectrefresh.emit())
        leftLayout.addWidget(updateButton)
        
        # Create New Test
        createButton = QPushButton("Create")
        createButton.clicked.connect(lambda: self.tester.createnewtest.emit())
        leftLayout.addWidget(createButton)

        self.tester.projectrefresh.connect(self.testlistRefresh)
        
        return leftLayout

    @Slot()
    def testlistRefresh(self):
        print("testlistRefresh")
        self.testList.settestfs(self.tester.fs)

    def initDataProcessorWidget(self):
        
        widget = QWidget()
        
        self.dataProcessorOutput = DataProcessorView()
        
        self.dataOptions = QPushButton("Options")
        self.dataOptions.clicked.connect(self.tester.getargs)
        
        self.dataProcessorRun = QPushButton("Execute")
        self.dataProcessorRun.clicked.connect(lambda: self.tester.processtest.emit())
        
        self.dataProcessorImportRaw = QPushButton("Import Raw Files")
        self.dataProcessorImportRaw.clicked.connect(lambda: self.tester.processtestimport.emit())
        
        h12	= QHBoxLayout()
        h12.addStretch(stretch=100)
        h12.addWidget(self.dataOptions)
        h12.addWidget(self.dataProcessorImportRaw)
        h12.addWidget(self.dataProcessorRun)
        
        q12 = QWidget()
        q12.setLayout(h12)
        
        v1	= QVBoxLayout()
        v1.addWidget(self.dataProcessorOutput)
        v1.addWidget(q12)
        
        widget.setLayout(v1)
        
        self.dataProcessorOutput.init()
        self.testitemchanged.connect(lambda x: print("Item changed!", type(x), x))
        self.testitemchanged.connect(lambda: self.tester.processtestclear.emit())
        
        def initDataProcessorWidget_append(html):
            htmlFmt = """
            <div style='white-space: pre; font-family: "Courier New", Courier, monospace; font-size: 10; '> 
            {}
            </div>
            <br>\n
            """
            
            self.dataProcessorOutput.moveCursor(QTextCursor.End)
            self.dataProcessorOutput.insertHtml(formatHtmlBlock(htmlFmt).format(html))
            self.dataProcessorOutput.moveCursor(QTextCursor.End)
        
        self.tester.processtestupdate.connect(initDataProcessorWidget_append)
        self.tester.processtestclear.connect(self.dataProcessorOutput.clear)
        
        return widget
    
    def initTestPageWebView(self):
        
        widget = QWidget()
        
        self.testPageWebView = TestPageWebView()
        refreshButton = QPushButton("Refresh")
        pdfButton = QPushButton("Save PDF")

        buttons = QWidget()
        h2 = QHBoxLayout()
        h2.addWidget(pdfButton)        
        h2.addWidget(refreshButton)     
        h2.setSizeConstraint(QLayout.SetFixedSize)
        buttons.setLayout(h2)        

        v1 = QVBoxLayout()
        v1.addWidget(self.testPageWebView)        
        v1.addWidget(buttons)     
        widget.setLayout(v1)
        
        self.testPageWebView.init()
        
        def setitem(testobj):
            # set testfolder item
            self.tester.setitem(testobj)
            
            # set
            if testobj:
                testhtml, testurl, testhtmlpath = self.tester.getinfopanelhtml(testobj)
                
                if testhtmlpath:
                    self._testhtmlpathpdf = testhtmlpath.with_suffix(".pdf")
                    self.printer.setOutputFileName(str(self._testhtmlpathpdf))
                    
                testqurl = QUrl("file://{}/".format(testurl.resolve()))
                self.testPageWebView.setHtml(testhtml, testqurl)
                    
                
            else:
                self.testPageWebView.setHtml("<html></html>", QUrl())
        
        # Connect Buttons
        self.testitemchanged.connect(lambda obj: setitem(obj) )
        refreshButton.clicked.connect(lambda obj: setitem(self.__current_item) )
        
        ## Save PDF Button
        self.printer = QPrinter()
        self.printer.setPageSize(QPrinter.A4)
        self.printer.setOutputFormat(QPrinter.PdfFormat)
 
        def savePdf():
            self.testPageWebView.print_(self.printer)
            
            msg = "PDF Saved: "+str(self._testhtmlpathpdf)
            print(msg)
            QMessageBox.information(self,"Information",msg)        
        
        pdfButton.clicked.connect(savePdf)
        
        return widget
        
    def initTestDataWebView(self):
        
        widget = QWidget()
        webView = TestPageWebView()
        
        refreshButton = QPushButton("Refresh")
        
        v1 = QVBoxLayout()
        v1.addWidget(webView)        
        v1.addWidget(refreshButton)     
        widget.setLayout(v1)
        
        ttfont = QFont("Monospace")
        ttfont.setStyleHint(QFont.TypeWriter)
        ttfont.setPointSize(8)
        webView.setFont(ttfont)
        webView.init()
        
        def setitem(testobj):

            if testobj:
                test = self.tester.getitem()
                # debug(test.folder.details)
                
                tables = []
                debug(test.folder.details) 
                details = Json.load_json_from(test.folder.details, defaultHandler=True)
                
                if not details:
                    webView.setHtml("<html></html>", QUrl())
                    return
                
                for key in details.keys():
                    if not isinstance(details[key], collections.Mapping):
                        tables.append("<h1>{}</h1><br>\n{}".format(key, str(details[key])))
                    else:
                        fdetails = sorted([ (k,v) for k,v in flatten(details[key]).items() ])
                        fdtable = tabulate.tabulate(fdetails, headers=["Key", "Value"], tablefmt="html")
                    
                        tables.append("<h2>{}</h2><br>\n\n{}".format(key, str(fdtable)))
                
                allfiles = [ [ f.relative_to(test.folder.main).as_posix(), ] for f in test.folder.main.rglob("**/*") ]
                allfilesTable = tabulate.tabulate( allfiles, headers=["All Files"], tablefmt="html")
                
                htmlFmt = """
                <style type="text/css">/*
                {defaultCss}
                </style>
                
                <div style='white-space: pre; font-family: "Courier New", Courier, monospace; font-size: 10; '> 
                # JSON Calculations:

                {fdtable}

                
                # All Files
                
                <br>
                
                {allfilesTable}
                
                </div>
                <br>
                """                
                webView.setHtml(formatHtmlBlock(htmlFmt).format(allfilesTable=allfilesTable,defaultCss=defaultCss, fdtable="<br>\n<br>\n".join(tables)))
            else:
                webView.setHtml("<html></html>", QUrl())
        
        def safe_setitem(testobj):
            try:
                setitem(testobj)
            except Exception as err:
                print(err.encoding("utf-8"))
        
        self.testitemchanged.connect(lambda obj: safe_setitem(obj) )
        refreshButton.clicked.connect(lambda obj: safe_setitem(self.__current_item) )
        
        self.testDataWebView = webView
        
        return widget
    
    @Slot(object)
    def updateTestItem(self, item):
        
        self.__current_item = item # probably not thread-safe
        self.tester.setitem(item)
        self.testitemchanged.emit(item)
        
    def initUI(self):

        self.tester = TestHandler(self)
        
        self.starttestitemchanged.connect(self.updateTestItem)
        
        self.testPanelTabs = QTabWidget(self)
        self.testPanelTabs.addTab(self.initDataProcessorWidget(), "Data Processor")
        self.testPanelTabs.addTab(self.initTestPageWebView(), "Summary Report")
        self.testPanelTabs.addTab(self.initTestDataWebView(), "Variables / Data")
        
        self.testInfoPanel = self.infoTestInfoPanel()
        self.testProtocolView = TestProtocolView(self)
        self.testitemchanged.connect(self.testProtocolView.update)
        
        lFrame = QFrame(self)
        lFrame.setLayout(self.testInfoPanel)

        # self.testProtocolView.setWidgetResizable(True)
        # self.testPanelTabs.setWidgetResizable(True)

        self.testSplitter = QSplitter(self)
        self.testSplitter.addWidget(self.testProtocolView)
        self.testSplitter.addWidget(self.testPanelTabs)
        # self.testLabel.setWidgetResizable(False)
        self.testSplitter.setStretchFactor(0, 1)
        self.testSplitter.setStretchFactor(1, 2)

        # self.testSplitter.setWidgetResizable(True)
        testPanelsLayout = QVBoxLayout()
        # testPanelsLayout.addWidget(self.testLabel)
        testPanelsLayout.addWidget(self.testSplitter)
        
        self.testPanels = QFrame(self)
        self.testPanels.setLayout(testPanelsLayout)
        
        # == Main Panel Init ==
        mainPanel = QSplitter(self)
        mainPanel.addWidget(lFrame)
        mainPanel.addWidget(self.testPanels)
        
        mainLayout = QVBoxLayout()
        
        self.setCentralWidget(mainPanel)
        
        self.statusBar()

        refresh = QAction(QIcon.fromTheme('refresh.png'), 'Refresh', self)
        refresh.setShortcut('Ctrl+R')
        refresh.triggered.connect(lambda: self.tester.projectrefresh.emit())
        
        mainToolbar = self.addToolBar("Main")
        mainToolbar.addAction(refresh)
        mainToolbar.addSeparator()
        
        dropdown, openfile = self.dropdownfilebox(self.tester)
        mainToolbar.addWidget(dropdown)
        mainToolbar.addAction(openfile)

        self.setWindowTitle('Project Test DataProcessor')
        
        self.show()
    
    def dropdownfilebox(self, tester):
        
        def getfiledialogdir():
            return json.loads(self.settings.value("dropdownfilebox/previousprojs", "[]"))
            
        filedialogdir = getfiledialogdir()
        
        combobox = QComboBox(self)
        combobox.setEditable(True)
        combobox.addItems(getfiledialogdir())
        combobox.setEditText("")
        combobox.setCurrentIndex(-1)
        
        @Slot(str)
        def dropdownfilebox_history(projdir):
            # update dropdown box
            previousprojs = [ combobox.itemText(idx) for idx in range(combobox.count()) ]
            
            if projdir in previousprojs: 
                idx = previousprojs.index(projdir)
                combobox.setCurrentIndex(idx)
            else:
                previousprojs.insert(0,str(projdir))
                combobox.insertItem(0,str(projdir))
                combobox.setCurrentIndex(0)
                
                print("Dropdown project history update:", previousprojs)
                self.settings.setValue("dropdownfilebox/previousprojs", json.dumps(previousprojs))
            
            combobox.setEditText( Path(projdir).name )
            self.tester.projectrefresh.emit()
            
        
        @Slot(int)
        def dropdownfilebox_selected(idx):
            debug("dropdownfilebox_selected", idx)
            projdir = combobox.itemText(idx)
            tester.setprojdir(projdir)
            
        combobox.activated.connect(dropdownfilebox_selected)
        tester.projectdirchanged.connect(dropdownfilebox_history)
        
        openfile = QAction(QIcon.fromTheme('open.png'), 'Open', self)
        openfile.setShortcut('Ctrl+O')
        openfile.triggered.connect(self.showFileDialog)
        
        # button.clicked.connect(self.showFileDialog)
        # return button
        return combobox, openfile

    def showFileDialog(self):
        filedialogdir = self.settings.value("dropdownfilebox/filedialogdir", os.path.expanduser("~/"))
        debug(filedialogdir)
        
        fname = QFileDialog.getExistingDirectory(self, 'Choose Project Directory', filedialogdir)
        if not fname:
            return
            
        debug(fname)
        self.settings.setValue("dropdownfilebox/filedialogdir", fname)
        self.tester.setprojdir(fname)
Exemplo n.º 50
0
    def toPdf(self, image):
        printer = QPrinter()
        printer.setPaperSize(QSizeF(210, 297), QPrinter.Millimeter)
        printer.setResolution(600)
        printer.setOutputFormat(QPrinter.PdfFormat)
        printer.setOutputFileName(self.get_path_to_revealer_file('.pdf'))
        printer.setPageMargins(0,0,0,0,6)
        painter = QPainter()
        painter.begin(printer)

        delta_h = round(image.width()/self.abstand_v)
        delta_v = round(image.height()/self.abstand_h)

        size_h = 2028+((int(self.calibration_h)*2028/(2028-(delta_h*2)+int(self.calibration_h)))/2)
        size_v = 1284+((int(self.calibration_v)*1284/(1284-(delta_v*2)+int(self.calibration_v)))/2)

        image =  image.scaled(size_h, size_v)

        painter.drawImage(553,533, image)
        wpath = QPainterPath()
        wpath.addRoundedRect(QRectF(553,533, size_h, size_v), 19, 19)
        painter.setPen(QPen(Qt.black, 1))
        painter.drawPath(wpath)
        painter.end()
Exemplo n.º 51
0
    def printImage(self):
        if self.model.rowCount(QModelIndex()) * self.model.columnCount(QModelIndex()) > 90000:
            answer = QMessageBox.question(self, "Large Image Size",
                    "The printed image may be very large. Are you sure that "
                    "you want to print it?",
                    QMessageBox.Yes | QMessageBox.No)
            if answer == QMessageBox.No:
                return

        printer = QPrinter(QPrinter.HighResolution)

        dlg = QPrintDialog(printer, self)
        dlg.setWindowTitle("Print Image")

        if dlg.exec_() != QDialog.Accepted:
            return

        painter = QPainter()
        painter.begin(printer)

        rows = self.model.rowCount(QModelIndex())
        columns = self.model.columnCount(QModelIndex())
        sourceWidth = (columns+1) * ItemSize
        sourceHeight = (rows+1) * ItemSize

        painter.save()

        xscale = printer.pageRect().width() / float(sourceWidth)
        yscale = printer.pageRect().height() / float(sourceHeight)
        scale = min(xscale, yscale)

        painter.translate(printer.pageRect().x()+printer.pageRect().width()/2,
                          printer.pageRect().y()+printer.pageRect().height()/2)
        painter.scale(scale, scale)
        painter.translate(-sourceWidt/2, -sourceHeight/2)

        option = QStyleOptionViewItem()
        parent = QModelIndex()

        progress = QProgressDialog("Printing...", "Cancel", 0, rows, self)
        y = ItemSize / 2.0

        for row in range(rows):
            progress.setValue(row)
            QApplication.processEvents()
            if progress.wasCanceled():
                break

            x = ItemSize / 2.0

            for col in range(columns):
                option.rect = QRect(x, y, ItemSize, ItemSize)
                self.view.itemDelegate.paint(painter, option,
                        self.model.index(row, column, parent))
                x = x + ItemSize

            y = y + ItemSize

        progress.setValue(rows)

        painter.restore()
        painter.end()

        if progress.wasCanceled():
            QMessageBox.information(self, "Printing canceled",
                    "The printing process was canceled.", QMessageBox.Cancel)
Exemplo n.º 52
0
	def standardPrinter(self, title):
		printer = QPrinter(QPrinter.HighResolution)
		printer.setDocName(title)
		printer.setCreator('ReText %s' % app_version)
		return printer
Exemplo n.º 53
0
 def __printImage(self):
     """
     Private slot to handle the Print Image menu action.
     """
     if self.mainWidget is None:
         E5MessageBox.critical(
             self,
             self.tr("Print Image"),
             self.tr("""There is no UI file loaded."""))
         return
     
     settings = Preferences.Prefs.settings
     printer = QPrinter(QPrinter.HighResolution)
     printer.setFullPage(True)
     
     printerName = Preferences.getPrinter("UIPreviewer/printername")
     if printerName:
         printer.setPrinterName(printerName)
     printer.setPageSize(
         QPrinter.PageSize(int(settings.value("UIPreviewer/pagesize"))))
     printer.setPageOrder(
         QPrinter.PageOrder(int(settings.value("UIPreviewer/pageorder"))))
     printer.setOrientation(QPrinter.Orientation(
         int(settings.value("UIPreviewer/orientation"))))
     printer.setColorMode(
         QPrinter.ColorMode(int(settings.value("UIPreviewer/colormode"))))
     
     printDialog = QPrintDialog(printer, self)
     if printDialog.exec_() == QDialog.Accepted:
         self.statusBar().showMessage(self.tr("Printing the image..."))
         self.__print(printer)
         
         settings.setValue("UIPreviewer/printername", printer.printerName())
         settings.setValue("UIPreviewer/pagesize", printer.pageSize())
         settings.setValue("UIPreviewer/pageorder", printer.pageOrder())
         settings.setValue("UIPreviewer/orientation", printer.orientation())
         settings.setValue("UIPreviewer/colormode", printer.colorMode())
     
     self.statusBar().showMessage(
         self.tr("Image sent to printer..."), 2000)
Exemplo n.º 54
0
 def filePrintPdf(self, fn):
     printer = QPrinter(QPrinter.HighResolution)
     printer.setPageSize(QPrinter.A4)
     printer.setOutputFileName(fn)
     printer.setOutputFormat(QPrinter.PdfFormat)
     self.document().print_(printer)
Exemplo n.º 55
0
 def __printPreviewImage(self):
     """
     Private slot to handle the Print Preview menu action.
     """
     from PyQt5.QtPrintSupport import QPrintPreviewDialog
     
     if self.mainWidget is None:
         E5MessageBox.critical(
             self,
             self.tr("Print Preview"),
             self.tr("""There is no UI file loaded."""))
         return
     
     settings = Preferences.Prefs.settings
     printer = QPrinter(QPrinter.HighResolution)
     printer.setFullPage(True)
     
     printerName = Preferences.getPrinter("UIPreviewer/printername")
     if printerName:
         printer.setPrinterName(printerName)
     printer.setPageSize(
         QPrinter.PageSize(int(settings.value("UIPreviewer/pagesize"))))
     printer.setPageOrder(
         QPrinter.PageOrder(int(settings.value("UIPreviewer/pageorder"))))
     printer.setOrientation(QPrinter.Orientation(
         int(settings.value("UIPreviewer/orientation"))))
     printer.setColorMode(
         QPrinter.ColorMode(int(settings.value("UIPreviewer/colormode"))))
     
     preview = QPrintPreviewDialog(printer, self)
     preview.paintRequested.connect(self.__print)
     preview.exec_()
Exemplo n.º 56
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
Exemplo n.º 57
0
    def calibration_pdf(self, image):
        printer = QPrinter()
        printer.setPaperSize(QSizeF(210, 297), QPrinter.Millimeter)
        printer.setResolution(600)
        printer.setOutputFormat(QPrinter.PdfFormat)
        printer.setOutputFileName(self.get_path_to_calibration_file())
        printer.setPageMargins(0,0,0,0,6)

        painter = QPainter()
        painter.begin(printer)
        painter.drawImage(553,533, image)
        font = QFont('Source Sans Pro', 10, QFont.Bold)
        painter.setFont(font)
        painter.drawText(254,277, _("Calibration sheet"))
        font = QFont('Source Sans Pro', 7, QFont.Bold)
        painter.setFont(font)
        painter.drawText(600,2077, _("Instructions:"))
        font = QFont('Source Sans Pro', 7, QFont.Normal)
        painter.setFont(font)
        painter.drawText(700, 2177, _("1. Place this paper on a flat and well iluminated surface."))
        painter.drawText(700, 2277, _("2. Align your Revealer borderlines to the dashed lines on the top and left."))
        painter.drawText(700, 2377, _("3. Press slightly the Revealer against the paper and read the numbers that best "
                                      "match on the opposite sides. "))
        painter.drawText(700, 2477, _("4. Type the numbers in the software"))
        painter.end()
Exemplo n.º 58
0
 def to_pdf(self, filename):
     printer = QPrinter()
     printer.setOutputFileName(filename)
     self.to_printer(printer)
Exemplo n.º 59
0
 def calibration_pdf(self, image):
     printer = QPrinter()
     printer.setPaperSize(QSizeF(210, 297), QPrinter.Millimeter);
     printer.setResolution(600)
     printer.setPageMargins(0,0,0,0, QPrinter.Millimeter)
     printer.setOutputFormat(QPrinter.PdfFormat)
     printer.setOutputFileName(self.base_dir+'calibration.pdf')
     painter = QPainter()
     painter.begin(printer)
     image =  image.scaled(self.size[0]*6.68,self.size[1]*6.68)
     #tuning
     font = QFont('Source Sans Pro', 27, QFont.Black)
     painter.setFont(font)
     
     cal_value = 0
     for p in range (1,2):
         for x in range (2):
             for n in range(5):
                 cal_value+=1
                 painter.drawImage(254+(x*2296),130+(n*1326),image.scaled(2022+cal_value,1274+cal_value))
                 painter.drawText(354+(x*2296),270+(n*1326), str(cal_value))
                 
         printer.newPage()
     painter.end()