Example #1
0
 def print_(self):
     try:
         p = qt.QPrinter(qt.QPrinter.HighResolution)
     except AttributeError:
         p = qt.QPrinter()
     p.setColorMode(qt.QPrinter.Color)
     p.setOutputToFile(True)
     if p.setup():
         self.__plot.print_(p)
Example #2
0
def testPreview():
    """
    """
    import sys
    import os.path

    if len(sys.argv) < 2:
        print("give an image file as parameter please.")
        sys.exit(1)

    if len(sys.argv) > 2:
        print("only one parameter please.")
        sys.exit(1)

    filename = sys.argv[1]

    a = qt.QApplication(sys.argv)
 
    p = qt.QPrinter()
    #p.setPrintToFile(1)
    p.setOutputToFile(1)
    p.setOutputFileName(os.path.splitext(filename)[0]+".ps")
    p.setColorMode(qt.QPrinter.Color)

    w = PrintPreview( parent = None, printer = p, name = 'Print Prev',
                      modal = 0, fl = 0)
    w.resize(400,500)

    w.addPixmap(qt.QPixmap(qt.QImage(filename)))
    #w.addImage(qt.QImage(filename))
    w.addImage(qt.QImage(filename))

    w.exec_loop()
Example #3
0
 def __webViewFormLoadedCallback__(self, loaded):
     if loaded:
         #outputFileName = os.path.join(self.getCurrentDataFolder(), "report.pdf")
         printer = qt.QPrinter(qt.QPrinter.HighResolution)
         printer.setOutputFormat(qt.QPrinter.PdfFormat)
         printer.setOutputFileName(self.__pdfOutputPath__)
         self.webView.print_(printer)
         self.webView.close()
         # Call the callback
         self.__callbackFunction__(self.__pdfOutputPath__)
         self.__callbackFunction__ = None
    def print_(self):
        printer = Qt.QPrinter(Qt.QPrinter.HighResolution)

        #docName = self.plot.title.text().
        printer.setOrientation(Qt.QPrinter.Landscape)
        printer.setColorMode(Qt.QPrinter.Color)
        printer.setOutputToFile(True)
        printer.setOutputFileName('bode-example-%s.ps' % Qt.qVersion())
        if printer.setup():
            filter = PrintFilter()
            if (Qt.QPrinter.GrayScale == printer.colorMode()):
                filter.setOptions(
                    Qwt.QwtPlotPrintFilter.PrintAll
                    & ~Qwt.QwtPlotPrintFilter.PrintCanvasBackground)
            self.plot.print_(printer, filter)
Example #5
0
 def __webViewFormLoadedCallback__(self, loaded):
     """ Function that is invoked when a webview has finished loading a URL
     :param loaded:
     """
     if loaded:
         outputFileName = os.path.join(self.getCurrentDataFolder(),
                                       "report.pdf")
         printer = qt.QPrinter(qt.QPrinter.HighResolution)
         printer.setOutputFormat(qt.QPrinter.PdfFormat)
         printer.setOutputFileName(outputFileName)
         self.webView.print_(printer)
         self.webView.close()
         # Call the callback
         self.callback(outputFileName)
         self.callback = None
Example #6
0
    def printPdf(
        self,
        htmlTemplatePath,
        values,
        callbackFunction,
        pdfOutputPath=None,
        imagesFileList=None,
        tempHtmlFolder=None,
    ):
        """
        Print a pdf file with the html stored in htmlPath and the specified values
        :param htmlTemplatePath: path to the html file that contains the template
        :param values: dictionary of values that will be used to build the final html
        :param callbackFunction: function that will be called when the process has finished (it is an asynchronous process)
        :param pdfOutputPath: path to the pdf file that will be created (if none, it will be saved in a temp file)
        :param imagesFileList: list of full paths to images that may be needed to generate the report
        :param tempHtmlFolder: folder where all the intermediate files will be stored. If none, a temporary folder will be used
        """
        if tempHtmlFolder is None:
            tempHtmlFolder = tempfile.mkdtemp()

        self.__pdfOutputPath__ = pdfOutputPath if pdfOutputPath is not None else os.path.join(
            tempHtmlFolder, "report.pdf")
        self.__callbackFunction__ = callbackFunction

        # Generate the Html
        with open(htmlTemplatePath, "r") as f:
            html = f.read()
        for key, value in values.items():
            html = html.replace(key, value)

        # If we need images, copy them to the temporary folder
        if imagesFileList:
            for im in imagesFileList:
                fileName = os.path.basename(im)
                shutil.copy(im, os.path.join(tempHtmlFolder, fileName))

        if hasattr(qt, 'QWebView'):
            # Save the file in the temporary folder
            htmlPath = os.path.join(tempHtmlFolder, "temp__.html")
            with open(htmlPath, "w") as f:
                f.write(html)
            logging.debug("Html generated in {}".format(htmlPath))
            # Create a web browser for rendering html
            self.webView = qt.QWebView()
            self.webView.settings().setAttribute(
                qt.QWebSettings.DeveloperExtrasEnabled, True)
            self.webView.connect('loadFinished(bool)',
                                 self.__webViewFormLoadedCallback__)
            u = qt.QUrl(htmlPath)
            self.webView.setUrl(u)
            self.webView.show()
        else:
            printer = qt.QPrinter(qt.QPrinter.PrinterResolution)
            printer.setOutputFormat(qt.QPrinter.PdfFormat)
            printer.setPaperSize(qt.QPrinter.A4)
            printer.setOutputFileName(self.__pdfOutputPath__)

            doc = qt.QTextDocument()
            doc.setHtml(html)
            doc.baseUrl = qt.QUrl.fromLocalFile(tempHtmlFolder + "/")
            doc.setPageSize(qt.QSizeF(
                printer.pageRect().size()))  # hide the page number
            doc.print(printer)

            # Call the callback
            self.__callbackFunction__(self.__pdfOutputPath__)
            self.__callbackFunction__ = None
Example #7
0
    def __init__(self, parent = None, printer = None, name = "PrintPreview", \
                 modal = 0, fl = 0):
        """
        Constructor method:

        """
        qt.QDialog.__init__(self, parent, name, modal, fl)

        self.printer    = None

        # main layout 
        layout = qt.QVBoxLayout(self, 0, -1, "PrintPreview global layout")

        toolBar = qt.QWidget(self)

        # Margin
        marginLabel = qt.QLabel("Margins:", toolBar)    
        self.marginSpin = qt.QSpinBox(0, 50, 10, toolBar)
        self.connect(self.marginSpin, qt.SIGNAL("valueChanged(int)"),    \
                     self.__marginChanged)

        # Scale / Zoom
        scaleLabel = qt.QLabel("Zoom:", toolBar)
        scaleCombo = qt.QComboBox(toolBar)
        self.scaleValues = [20, 40, 60, 80, 100, 150, 200]

        for scale in self.scaleValues:
            scaleCombo.insertItem("%3d %%"%scale)
            
        self.scaleCombo = scaleCombo
        self.connect(self.scaleCombo, qt.SIGNAL("activated(int)"),        \
                     self.__scaleChanged)


        # --- command buttons
        buttonSize = 65
        
        hideBut   = qt.QPushButton("Hide", toolBar)
        hideBut.setFixedWidth(buttonSize-10)
        self.connect(hideBut, qt.SIGNAL("clicked()"), self.hide)

        cancelBut = qt.QPushButton("Clear All", toolBar)
        cancelBut.setFixedWidth(buttonSize+10)
        self.connect(cancelBut, qt.SIGNAL("clicked()"), self.__clearAll)

        removeBut = qt.QPushButton("Remove", toolBar)
        removeBut.setFixedWidth(buttonSize)
        self.connect(removeBut, qt.SIGNAL("clicked()"), self.__remove)

        setupBut  = qt.QPushButton("Setup", toolBar)
        setupBut.setFixedWidth(buttonSize-5)
        self.connect(setupBut, qt.SIGNAL("clicked()"), self.__setup)

        printBut  = qt.QPushButton("Print", toolBar)
        printBut.setFixedWidth(buttonSize-5)
        self.connect(printBut, qt.SIGNAL("clicked()"), self.__print)
        
        # a layout for the toolbar
        toolsLayout = qt.QHBoxLayout(toolBar, 0, -1, "Tools Layout")

        # now we put widgets in the toolLayout
        toolsLayout.addWidget(hideBut)
        toolsLayout.addWidget(printBut)
        toolsLayout.addWidget(cancelBut)
        toolsLayout.addWidget(removeBut)
        toolsLayout.addWidget(setupBut)
        toolsLayout.addStretch()
        toolsLayout.addWidget(marginLabel)
        toolsLayout.addWidget(self.marginSpin)    
        toolsLayout.addStretch()
        toolsLayout.addWidget(scaleLabel)
        toolsLayout.addWidget(scaleCombo)
        toolsLayout.addStretch()

        # canvas to display items to print
        self.canvas     = qtcanvas.QCanvas(self)
        self.canvasView = PrintCanvasView(self.canvas, self)

        # status bar
        statusBar = qt.QStatusBar(self)

        self.targetLabel = qt.QLabel( "???", statusBar, "targetLabel")
        statusBar.addWidget(self.targetLabel)

        # finally, building main widget.
        layout.addWidget(toolBar)
        layout.addWidget(self.canvasView)
        layout.addWidget(statusBar)
        
        # use user printer or a default QPrinter
        if printer == None:
            printer = qt.QPrinter()
            
        self.setPrinter(printer)
Example #8
0
    def __init__(self, *args):
        BlissWidget.__init__(self, *args)

        self.camera       = None
        self.update_disabled = False
        self.__cameraName = None

        self.__zoomList = [1.5,2,2.5,3,3.5,4]
        self.__initZoom = 2

        self.__fixWidth  = -1
        self.__fixHeight = -1

        self.__swapRgb = True
                        ####### PRINT #######
        self.__printWidget = QubPrintPreview(self)
        self.__printWidget.resize(400,500)
        printer = qt.QPrinter()
        printer.setOutputToFile(1)
        printer.setOutputFileName('/tmp/print_file.ps')
        self.__printWidget.setPrinter(printer)
        self.__printWidget.update()

        self.__beamAction    = None
        self.__scaleAction   = None
        self.__chosenActions = {}
        self.__wholeActions  = []
        self.__measureDialog = None

        ####### PRINT ACTION #######
        printAction = QubPrintPreviewAction(name="print",group="admin",withVectorMenu=True)
        printAction.previewConnect(self.__printWidget)
        self.__wholeActions.append(printAction)

        ####### SAVE IMAGE #######
        self.__saveAction = QubSaveImageAction(parent=self, label='Save falcon image',
                                               name="save", group="admin")
        self.__saveAction.setConnectCallBack(self._save_dialog_new)
        self.__wholeActions.append(self.__saveAction)
        self.__defaultSavePath = '/tmp'

        ####### UPDATE #######
        update = QubToggleAction(name="update",group="image",initState=True)
        self.connect(update,qt.PYSIGNAL("StateChanged"),self.__cameraUpdate)
        self.__wholeActions.append(update)

        ####### Start Camera ######
        startCamera = QubToggleAction(name="startCamera", group="image", iconName = 'bright-cont', initState=True)
        self.connect(startCamera, qt.PYSIGNAL("StateChanged"), self.__cameraStart)
        self.__wholeActions.append(startCamera)


        ####### BRIGHTNESS/CONTRAST #######
        self.__brightcount = QubOpenDialogAction(name="bright-cont",
                                                 iconName = 'bright-cont', group="image")
        self.__brightcount.setDialog(QubBrightnessContrastDialog(self))
        self.__wholeActions.append(self.__brightcount)

        ###### Grid TOOL ######
        self.__gridToolAction = QubOpenDialogAction(parent=self, name='grid_tool',
                                                    iconName='rectangle', label='Grid tool',
                                                    group="Tools") #place="contextmenu")
        self.__gridDialog = GridDialog(self, "Grid Dialog", flags = qt.Qt.WStyle_StaysOnTop)
        self.__gridToolAction.setConnectCallBack(self._grid_dialog_connect_hdlr)
        self.__wholeActions.append(self.__gridToolAction)

        self.__previous_pos_dict = {}
        self.__beamWidth = 0
        self.__beamHeight = 0

        ####### BEAM ACTION #######
        self.__beamAction = QubBeamAction(name="beam", group="Tools")
        self.__wholeActions.append(self.__beamAction)
        self.connect(self.__beamAction,qt.PYSIGNAL("BeamSelected"),
                     self.beamSelection)

        ####### SCALE #######
        self.__scaleAction = QubScaleAction(name='scale',group='Tools')
        self.__wholeActions.append(self.__scaleAction)
        self.__wholeActions.extend(self.__creatStdActions())

        ####### ACTION INFO #######
        actionInfo = QubInfoAction(name="actionInfo", group="image",place="statusbar")
        self.__wholeActions.append(actionInfo)

        ####### CHANGE FOREGROUND COLOR #######
        self.__fcoloraction = QubForegroundColorAction(name="color", group="image")
        self.__wholeActions.append(self.__fcoloraction)

        ####### MEASURE #######
        self.__measureAction = QubOpenDialogAction(parent=self, name='measure',
                                            iconName='measure', label='Measure',
                                            group="Tools")
        self.__measureAction.setConnectCallBack(self._measure_dialog_new)
        self.__wholeActions.append(self.__measureAction)

        # ###### POSITION TOOL ######
        # self.__posToolAction = QubOpenDialogAction(parent=self, name='pos_tool',
        #                                            iconName='circle', label='Position tool',
        #                                            group="Tools")
        # self.__posToolAction.setConnectCallBack(self._line_dialog_new)
        # self.__wholeActions.append(self.__posToolAction)

        ####### ZOOM LIST #######
        zoomActionList = QubZoomListAction(place = "toolbar",
                                           initZoom = 1,zoomValList = [0.1,0.25,0.5,0.75,1,1.5,2],
                                           show = 1,group = "zoom")
        self.__wholeActions.append(zoomActionList)

        ####### ZOOM Action #######
        self.__zoomFitOrFill = QubZoomAction(place = "toolbar",group = "zoom")
        self.__wholeActions.append(self.__zoomFitOrFill)

        ####### LINK ZOOM ACTION #######
        self.__zoomFitOrFill.setList(zoomActionList)
        zoomActionList.setActionZoomMode(self.__zoomFitOrFill)

        ####### ZOOM WINDOW #######
        self.__zoomAction = QubZoomRectangle(label='Zoom Crop',place="toolbar", show=1, group="zoom")
        self.connect(self.__zoomAction,qt.PYSIGNAL("Actif"),self.__hide_show_zoom)
        self.__wholeActions.append(self.__zoomAction)

        self.__splitter = qt.QSplitter(qt.Qt.Horizontal,self)
        self.__splitter.show()

        self.__mainVideo = QubPixmapDisplayView(self.__splitter)
        self.__mainVideo.show()
        self.__mainVideo.setScrollbarMode('Auto')
        self.__mainPlug = _MainVideoPlug(self.__mainVideo,self.__zoomAction)

        actions = self.__creatStdActions()

        ####### ZOOM LIST #######
        self.__zoomActionList = QubZoomListAction(place = "toolbar",keepROI = True,
                                                  initZoom = self.__initZoom,zoomValList = self.__zoomList,
                                                  show = 1,group = "zoom")
        actions.insert(0,self.__zoomActionList)

        ####### ZOOM Action #######
        zoomFitOrFill = QubZoomAction(place = "toolbar",keepROI = True,group = "zoom")
        zoomFitOrFill.setList(self.__zoomActionList)
        self.__zoomActionList.setActionZoomMode(zoomFitOrFill)
        actions.append(zoomFitOrFill)

        self.__zoomVideo = QubPixmapDisplayView(self.__splitter,None,actions)
        self.__zoomVideo.hide()
        self.__zoomPlug = _ZoomPlug(self.__zoomVideo)
        self.__zoomPlug.zoom().setZoom(2,2)
        self.__cbk = _rectangleZoom(self.__zoomAction,self.__zoomPlug)

        layout = qt.QHBoxLayout(self,0,0,"layout")
        layout.addWidget(self.__splitter)

        self.__image2Pixmap = QubImage2Pixmap()
        self.__image2Pixmap.plug(self.__mainPlug)
        self.__zoomPlug.setPoller(self.__image2Pixmap)

        self.__jpegDecompress = QubStdData2Image()
        self.__jpegDecompress.setSwapRGB(True)
        self.__jpeg2image = None

        ####### PROPERTY #######
        self.addProperty('camera','string','')
        self.addProperty('zoom list','string',','.join([str(x) for x in self.__zoomList]))
        self.addProperty('init zoom','integer',self.__initZoom)
        self.addProperty('swap rgb','boolean',True)

        self.addProperty('fix : width','integer',-1)
        self.addProperty('fix : height','integer',-1)

        self.addProperty('action : print','boolean',True)
        self.addProperty('action : save image','boolean',True)
        self.addProperty('action : update','boolean',True)
        self.addProperty('action : startCamera','boolean',True)
        self.addProperty('action : brightness contrast','boolean',True)
        self.addProperty('action : beam','boolean',True)
        self.addProperty('action : scale','boolean',True)
        self.addProperty('action : change foreground color','boolean',True)
        self.addProperty('action : measure','boolean',True)
        self.addProperty('action : measure (place)', 'combo', ('toolbar','contextmenu'),'toolbar')
        self.addProperty('action : zoom window','boolean',True)
        self.addProperty('action : zoom fit or fill','boolean',True)
        self.addProperty('action : zoom list','boolean',True)
        self.addProperty('action : x,y coordinates','boolean',True)
        self.addProperty('action : default color','combo',('black','red','green'),'black')

        self.addProperty('action : save image (place)',"combo",('toolbar','contextmenu'),'toolbar')
        self.addProperty('action : save image (default path)',"string",'/tmp')
        self.addProperty('action : save image (show always configure)',"boolean",True)

        self.addProperty("diffractometer", "string", "")
        self.diffractometerHwobj = None


        ####### SIGNAL #######
        self.defineSignal("BeamPositionChanged", ())

        ####### SLOT #######
        self.defineSlot("changeBeamPosition", ())
        self.defineSlot("changePixelScale",())
        self.defineSlot('getView',())
        self.defineSlot('getImage',())

        ####### LINK VIEW AND SUB VIEW #######
        mainView = self.__mainVideo.view()
        zoomView = self.__zoomVideo.view()
        mainView.addEventMgrLink(zoomView,
                                 mainView.canvas(),zoomView.canvas(),
                                 mainView.matrix(),zoomView.matrix())

        self.imageReceivedConnected = None