当前位置: 首页>>代码示例>>Python>>正文


Python QPrinter.newPage方法代码示例

本文整理汇总了Python中PyQt4.QtGui.QPrinter.newPage方法的典型用法代码示例。如果您正苦于以下问题:Python QPrinter.newPage方法的具体用法?Python QPrinter.newPage怎么用?Python QPrinter.newPage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PyQt4.QtGui.QPrinter的用法示例。


在下文中一共展示了QPrinter.newPage方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: print_pdf

# 需要导入模块: from PyQt4.QtGui import QPrinter [as 别名]
# 或者: from PyQt4.QtGui.QPrinter import newPage [as 别名]
	def print_pdf(self):
		if self.deck is not None:
			#Setting the printer
			printer = QPrinter(QPrinter.HighResolution)
			printer.setOutputFormat(QPrinter.PdfFormat)
			printer.setOrientation(getattr(QPrinter, "Portrait"))
			printer.setOutputFileName(self.path)
			printer.setPaperSize(getattr(QPrinter, self.paper))
			printer.setFullPage(True)
			guide = self.max_cards()
			printer.setOrientation(getattr(QPrinter, guide["orientation"]))
			print guide, self.card_size
			#Start printing
			with QPainter(printer) as paint:
				ind = 0
				resol = printer.resolution()
				for c in self.deck:
						c.resize(self.card_size[0], self.card_size[1])
						if ind == guide["max"]:
							printer.newPage()
							ind = 0

						col = ind % guide["horizontal"]
						fil = ind // guide["horizontal"]
						print ind, fil, col
						target = QRectF((col)*self.card_size[0]*resol, (fil)*self.card_size[1]*resol,
									self.card_size[0]*resol, self.card_size[1]*resol)

						self.preview_card(c)
						self.scene.render(paint, target=target, source=QRectF(0,0,c.width(),c.height()))
						ind += 1
开发者ID:Ja-vi,项目名称:pnp,代码行数:33,代码来源:printer.py

示例2: print_grid

# 需要导入模块: from PyQt4.QtGui import QPrinter [as 别名]
# 或者: from PyQt4.QtGui.QPrinter import newPage [as 别名]
	def print_grid(self):
		if self.deck is not None:
			#Setting the printer
			printer = QPrinter(QPrinter.HighResolution)
			printer.setOutputFormat(QPrinter.PdfFormat)
			printer.setOrientation(getattr(QPrinter, self.orientation))
			printer.setOutputFileName(self.path)
			printer.setPaperSize(getattr(QPrinter, self.paper))
			#Start printing
			with QPainter(printer) as paint:
				first = True
				for c in self.deck:
					if not first:
						printer.newPage()
					first = False
					self.preview_card(c)
					self.scene.render(paint)
开发者ID:Ja-vi,项目名称:pnp,代码行数:19,代码来源:printer.py

示例3: main

# 需要导入模块: from PyQt4.QtGui import QPrinter [as 别名]
# 或者: from PyQt4.QtGui.QPrinter import newPage [as 别名]
def main():
	app = QApplication(sys.argv)
	
	# Preparing the pdf
	doc = QTextDocument()
	printer = QPrinter()
	printer.setOutputFileName("KabitGurdas.pdf")
	printer.setOutputFormat(QPrinter.PdfFormat)
	
	# Setting page size as A5
	printer.setPaperSize(QPrinter.A5);
	# page margin
	
	printer.setPageMargins(12, 16, 12, 20, QPrinter.Millimeter)
	doc.setPageSize(QSizeF(printer.pageRect().size()))
	
	painter = QPainter()
	painter.begin( printer )	
	
	# Set poem book and get each poem in pdf
	book = kb()
	
	for KabitNumber in range(1,676):		
		# Add text in html to page
		doc.setHtml(book.getKabitHTML(KabitNumber))
		doc.defaultFont().setPointSize(20)
	
		# A new page
		printer.newPage()
		# Create a QPainter to draw our content    
		doc.drawContents(painter)#,printer.pageRect().translated( -printer.pageRect().x(), -printer.pageRect().y() ))
		#QTextDocument.drawContents(QPainter, QRectF rect=QRectF())
		doc.print_(printer)
	
	# Done.
	painter.end()
开发者ID:rusticmystic,项目名称:kabit_gurdas_bhalla,代码行数:38,代码来源:create_pdf.py

示例4: BatchPlottingDialog

# 需要导入模块: from PyQt4.QtGui import QPrinter [as 别名]
# 或者: from PyQt4.QtGui.QPrinter import newPage [as 别名]

#.........这里部分代码省略.........
                QApplication.setOverrideCursor( Qt.BusyCursor )
                
                for featureI in range(0, atlas.numFeatures()):
                    progress.setValue( featureI+1 )
                    # process input events in order to allow aborting
                    QCoreApplication.processEvents()
                    if progress.wasCanceled():
                        atlas.endRender()
                        break
                    if not atlas.prepareForFeature( featureI ):
                        QMessageBox.warning( self, tr( "Atlas processing error" ),
                              tr( "Atlas processing error" ) )
                        progress.cancel()
                        QApplication.restoreOverrideCursor()
                        return
                    if not self.ui.SingleFileCheckbox.checkState():
                        multiFilePrinter = QPrinter()
                        outputFileName = QDir( outputDir ).filePath( atlas.currentFilename() ) + ".pdf"
                        self.composition.beginPrintAsPDF( multiFilePrinter, outputFileName )
                        # set the correct resolution
                        self.composition.beginPrint( multiFilePrinter )
                        printReady = painter.begin( multiFilePrinter )
                        if not printReady:
                            QMessageBox.warning( self, tr( "Atlas processing error" ),
                                tr( "Error creating %s." % outputFileName ) )
                            progress.cancel()
                            QApplication.restoreOverrideCursor()
                            return
                        self.composition.doPrint( multiFilePrinter, painter )
                        painter.end()
                    else:
                        # start print on a new page if we're not on the first feature
                        if featureI > 0:
                            printer.newPage()
                        self.composition.doPrint( printer, painter )
                    
                atlas.endRender()
                if self.ui.SingleFileCheckbox.checkState():
                    painter.end()
                QApplication.restoreOverrideCursor()

            elif self.ui.OutputTab.currentIndex() == 1:  # to Printer
                # if To Printer is selected set the printer
                # setting up printer
                if self.printer is None:
                    self.printer = QPrinter()
                    self.printer.setFullPage(True)
                    self.printer.setColorMode(QPrinter.Color)
                # open printer setting dialog
                pdlg = QPrintDialog(self.printer,self)
                pdlg.setModal(True)
                pdlg.setOptions(QAbstractPrintDialog.None)
                if not pdlg.exec_() == QDialog.Accepted:
                    return
                
                QApplication.setOverrideCursor(Qt.BusyCursor)
                #prepare for first feature, so that we know paper size to begin with
                self.composition.setAtlasMode( QgsComposition.ExportAtlas )
                atlas.prepareForFeature(0)

                # set orientation                
                if self.composition.paperWidth() > self.composition.paperHeight():
                    self.printer.setOrientation(QPrinter.Landscape)
                    self.printer.setPaperSize(
                        QSizeF(self.composition.paperHeight(), self.composition.paperWidth()),
                        QPrinter.Millimeter)
开发者ID:GEO-IASS,项目名称:ls,代码行数:70,代码来源:batch_plotting_dialog.py

示例5: Printer

# 需要导入模块: from PyQt4.QtGui import QPrinter [as 别名]
# 或者: from PyQt4.QtGui.QPrinter import newPage [as 别名]
class Printer(BasePrinter):

    FONT_NAME = 'Courrier'

    def __init__(self, *args, **kwargs):
        BasePrinter.__init__(self, *args, **kwargs)
        self.page_number = 0

        self.printer = QPrinter(QPrinter.HighResolution)
        ## todo: remove-me
        self.printer.setOutputFileName("ufwi_log-page.pdf")
        self.printer.setOutputFormat(QPrinter.NativeFormat)
        #self.printer.setOrientation(QPrinter.Landscape)
        self.printer.setPaperSize(QPrinter.A4)
        self.printer.setResolution(100)

    def _init_painter(self):
        self.painter = QPainter(self.printer)
        self.painter.setRenderHint(QPainter.Antialiasing)
        self.painter.setBackgroundMode(Qt.OpaqueMode)
        self.painter.setBrush(Qt.white)
        self.painter.setFont(QFont(self.FONT_NAME, 9))
        fillrect = QRect(0, 0, self.printer.pageRect().width(), self.printer.pageRect().height())
        self.painter.fillRect(fillrect, self.painter.brush())
        self.page_number = 1

        self._draw_header()
        self._draw_footer()
        self.drawCentralTitle(self.title)
        if self.logo:
            self.painter.drawImage(QPoint(self.width() / 2 - self.logo.width() / 2,
                                          self.height() / 2 + QFontMetrics(self.painter.font()).height() + self.height() / 4 - self.logo.height() / 2),
                                   self.logo)

    def _draw_header(self):
        if not self.header_enabled:
            return

        h = -self.headerHeight()
        self.drawText(QDateTime.currentDateTime().toString('yyyy-MM-dd hh:mm'), h, Qt.AlignLeft)
        h += self.drawText(self.interval_label, h, Qt.AlignRight)
        self.drawText(self.title, h, Qt.AlignLeft)
        self.drawText(self.enterprise, h, Qt.AlignRight)

        self.painter.drawLine(0,
                              self.headerHeight() - 1,
                              self.printer.pageRect().width(),
                              self.headerHeight() - 1)

    def _draw_footer(self):
        if not self.footer_enabled:
            return

        self.painter.drawLine(10,
                              self.printer.pageRect().height() - self.footerHeight(),
                              self.printer.pageRect().width() - 10,
                              self.printer.pageRect().height() - self.footerHeight())
        h = self.height() + 1
        #self.drawText('topleft', h, Qt.AlignLeft)
        h += self.drawText(u'© 2008-2010 EdenWall', h, Qt.AlignRight, size=9)
        self.drawText(unicode(self.page_number), h, Qt.AlignHCenter)
        #self.drawText('bottomright', h, Qt.AlignRight)

    def headerHeight(self):
        if self.header_enabled:
            return 40
        else:
            return 0

    def footerHeight(self):
        if self.footer_enabled:
            return 40
        else:
            return 0

    def height(self):
        return self.printer.pageRect().height() - self.headerHeight() - self.footerHeight()

    def width(self):
        return self.printer.pageRect().width()

    def showDialog(self, parent):
        dialog = QPrintDialog(self.printer, parent)
        if dialog.exec_() != QPrintDialog.Accepted:
            return False

        self._init_painter()
        return True

    def end(self):
        self.painter.end()

    def newPage(self):
        self.printer.newPage()
        self.page_number += 1
        self._draw_header()
        self._draw_footer()

    def drawCentralTitle(self, text):
        self.painter.setBackgroundMode(Qt.TransparentMode)
#.........这里部分代码省略.........
开发者ID:maximerobin,项目名称:Ufwi,代码行数:103,代码来源:printer.py

示例6: export_all_features

# 需要导入模块: from PyQt4.QtGui import QPrinter [as 别名]
# 或者: from PyQt4.QtGui.QPrinter import newPage [as 别名]

#.........这里部分代码省略.........
            printer.setOutputFormat(QPrinter.PdfFormat)
            printer.setOutputFileName(self.pdf_map)
            printer.setPaperSize(QSizeF(composition.paperWidth(), composition.paperHeight()), QPrinter.Millimeter)
            printer.setFullPage(True)
            printer.setColorMode(QPrinter.Color)
            printer.setResolution(composition.printResolution())

            pdf_painter = QPainter(printer)
            paper_rect_pixel = printer.pageRect(QPrinter.DevicePixel)
            paper_rect_mm = printer.pageRect(QPrinter.Millimeter)
            QgsPaintEngineHack.fixEngineFlags(printer.paintEngine())
            #DKM only
            if len(self.themen) < 1:
                composition.render(pdf_painter, paper_rect_pixel, paper_rect_mm)
            else:
                self.statistics = OrderedDict()
                try:
                    pass
                    #lyr = QgsVectorLayer('/home/bergw/VoGIS-Raumplanung-Daten/Geodaten/Raumplanung/Flaechenwidmung/Dornbirn/Flaechenwidmungsplan/fwp_flaeche.shp', 'flaeiw', 'ogr')
                    #lyr.loadNamedStyle('/home/bergw/VoGIS-Raumplanung-Daten/Geodaten/Raumplanung/Flaechenwidmung/Vorarlberg/Flaechenwidmungsplan/fwp_flaeche.qml')
                    #QgsMapLayerRegistry.instance().addMapLayer(lyr)
                except:
                    QgsMessageLog.logMessage('new lyr:{0}'.format(sys.exc_info()[0]), DLG_CAPTION)
                #QgsMapLayerRegistry.instance().addMapLayer(lyr)
                cntr = 0
                for thema, sub_themen in self.themen.iteritems():
                    if VRP_DEBUG is True: QgsMessageLog.logMessage('drucke Thema:{0}'.format(thema.name), DLG_CAPTION)
                    if sub_themen is None:
                        layers = self.__add_layers(thema)
                        self.__calculate_statistics(thema, thema, layers)
                        #no qml -> not visible -> means no map
                        if self.__at_least_one_visible(layers) is True:
                            if cntr > 0:
                                printer.newPage()
                            self.__reorder_layers()
                            self.__update_composer_items(thema.name, layers=layers)
                            composition.renderPage(pdf_painter, 0)
                            QgsMapLayerRegistry.instance().removeMapLayers([lyr.id() for lyr in layers])
                            cntr += 1
                        else:
                            QgsMapLayerRegistry.instance().removeMapLayers([lyr.id() for lyr in layers])
                    if not sub_themen is None:
                        for sub_thema in sub_themen:
                            if VRP_DEBUG is True: QgsMessageLog.logMessage(u'drucke SubThema:{0}'.format(sub_thema.name), DLG_CAPTION)
                            layers = self.__add_layers(sub_thema)
                            self.__calculate_statistics(thema, sub_thema, layers)
                            #no qml -> not visible -> means no map
                            if self.__at_least_one_visible(layers) is True:
                                if cntr > 0:
                                    printer.newPage()
                                self.__reorder_layers()
                                self.__update_composer_items(thema.name, subthema=sub_thema.name, layers=layers)
                                composition.renderPage(pdf_painter, 0)
                                QgsMapLayerRegistry.instance().removeMapLayers([lyr.id() for lyr in layers])
                                cntr += 1
                            else:
                                QgsMapLayerRegistry.instance().removeMapLayers([lyr.id() for lyr in layers])
            #output statistics
            if len(self.statistics) > 0:
                printer.setPaperSize(QSizeF(210, 297), QPrinter.Millimeter)
                tabelle = self.__get_item_byid(self.comp_textinfo, 'TABELLE')
                if tabelle is None:
                    self.iface.messageBar().pushMessage(u'Layout (Textinfo): Kein Textelement mit ID "TABELLE" vorhanden.', QgsMessageBar.CRITICAL)
                else:
                    try:
                        str_flaechen = ''
开发者ID:BergWerkGIS,项目名称:VoGIS-Raumplanung,代码行数:70,代码来源:vrpprintcomposer.py

示例7: enumerate

# 需要导入模块: from PyQt4.QtGui import QPrinter [as 别名]
# 或者: from PyQt4.QtGui.QPrinter import newPage [as 别名]
    # max numbers in one line then add <br> in "english" translation
    no_of_words = 20
    for num, name in enumerate(Plist):
        k = Elist[num].split()
        klen = k.__len__()
        t = klen / no_of_words
        for i in range(t):
            k.insert(no_of_words * (i + 1), "<br>")
        strline = " ".join(k)
        htmllist.append(AddHTMLTag(Center(Italics(TextSize(strline, 3))), "p"))

    body = " ".join(htmllist)
    # Necessary for unicode rendering
    headuni = '<meta http-equiv="Content-Type" content="text\/html; charset=utf-8">'

    html[count] = AddHead(headuni) + AddBody(body)

    # A new page
    printer.newPage()

    # Draw the first page removing the pageRect offset due to margins.
    doc.setHtml(html[count])
    # Create a QPainter to draw our content

    doc.drawContents(painter)  # ,printer.pageRect().translated( -printer.pageRect().x(), -printer.pageRect().y() ))
    # QTextDocument.drawContents(QPainter, QRectF rect=QRectF())
    doc.print_(printer)

# Done.
painter.end()
开发者ID:rusticmystic,项目名称:demo_sources,代码行数:32,代码来源:kabit_pdf.py

示例8: Form

# 需要导入模块: from PyQt4.QtGui import QPrinter [as 别名]
# 或者: from PyQt4.QtGui.QPrinter import newPage [as 别名]

#.........这里部分代码省略.........
          self.filename = args[1]
        self.txtFileName.setReadOnly(True)
        btnGetFileName = QToolButton()
        btnGetFileName.setText("..")
        getFileLayout = QHBoxLayout()
        getFileLayout.addWidget(lblFileName)
        getFileLayout.addWidget(self.txtFileName)
        getFileLayout.addWidget(btnGetFileName)
        
        #Code page of file
        lblCodePage = QLabel("Code Page")
        self.cmbCodePage = QComboBox()
        self.cmbCodePage.addItem("dos")
        self.cmbCodePage.addItem("windows")
        self.cmbCodePage.addItem("utf8")
        codePageLayout = QHBoxLayout()
        codePageLayout.addStretch()
        codePageLayout.addWidget(lblCodePage)
        codePageLayout.addWidget(self.cmbCodePage)
       
        
        #Printer Orientation (Portrait / Landscape)
        lblOrientation = QLabel("Orientation")
        self.cmbOrientation = QComboBox()
        self.cmbOrientation.addItem("portait")
        self.cmbOrientation.addItem("landscape")
        orientationLayout = QHBoxLayout()
        orientationLayout.addStretch()
        orientationLayout.addWidget(lblOrientation)
        orientationLayout.addWidget(self.cmbOrientation)
        
        
        #Buttons for save or Just quit
        bSave = QPushButton("Go for it")
        bQuit = QPushButton("Abort")
        buttonLayout = QHBoxLayout()
        buttonLayout.addWidget(bQuit)
        buttonLayout.addStretch()
        buttonLayout.addWidget(bSave)
        
        #Final Layout
        layout = QVBoxLayout()
        layout.addLayout(getFileLayout)
        layout.addLayout(codePageLayout)
        layout.addLayout(orientationLayout)
        layout.addLayout(buttonLayout)
        self.setLayout(layout)
        
        #Connections
        self.connect(bSave, SIGNAL("clicked()"),self.printViaQPainter)
        self.connect(bQuit, SIGNAL("clicked()"), self.accept)
        self.connect(btnGetFileName, SIGNAL("clicked()"),self.getFileName)
        self.setWindowTitle("dos/windows text to PDF")
        
    def getFileName(self):
        fd = QFileDialog(self)
        self.filename = fd.getOpenFileName()
        self.txtFileName.setText(self.filename)
        
    def printViaQPainter(self):
        from os.path import isfile
        if isfile(self.filename):
            lines = open(self.filename)
        else:
            return
        a = self.filename.split('.')
        s = a[-1]
        fname = ''
        for i in range(len(a)-1) :
          fname += a[i]
        fname += '.pdf'        
        self.printer.setOutputFileName(fname)
        self.printer.setOutputFormat(QPrinter.PdfFormat)
        if self.cmbOrientation.currentText() == 'landscape':
            self.printer.setOrientation(QPrinter.Landscape)
        pageRect = self.printer.pageRect()
        LeftMargin = 15
        biggest = findBiggestLine(self.filename)
        bestSize = findBestFontSize(biggest,pageRect)
        sansFont = QFont("Courier", bestSize)
        sansLineHeight = QFontMetrics(sansFont).height()
        painter = QPainter(self.printer)
        page = 1
        y = 20
        cpage = codePage(self.cmbCodePage.currentText())
        for line in lines:
            painter.save()
            painter.setFont(sansFont)
            y += sansLineHeight
            x = LeftMargin
            try:
                painter.drawText(x,y,line[:-1].decode(cpage))
            except:
                painter.drawText(x,y,'CodePage error !!!')
            if y > (pageRect.height() - 54) :
                self.printer.newPage()
                y = 20
            painter.restore()
        lines.close()
        self.accept()
开发者ID:tedlaz,项目名称:m13,代码行数:104,代码来源:dw2pdf.py

示例9: Ui_py_de

# 需要导入模块: from PyQt4.QtGui import QPrinter [as 别名]
# 或者: from PyQt4.QtGui.QPrinter import newPage [as 别名]

#.........这里部分代码省略.........
        sizePolicy.setHeightForWidth(self.textEdit.sizePolicy().hasHeightForWidth())
        self.textEdit.setSizePolicy(sizePolicy)
        self.textEdit.setObjectName(newTextEditName)
        self.tablayout.addWidget(self.textEdit, 0, 0, 1, 1)


	#####################################
	## Functions for menu button actions
	#####################################

    def openFile(self):
        fileName = QFileDialog.getOpenFileName()
        print fileName
        index = fileName.lastIndexOf("/")
        newFileName = fileName[index+1:]
        print newFileName
        self.createTab(py_de, "", newFileName)
        self.textEdit.setText(open(fileName).read())

    def printFile(self): # Needs some work...
        printDialog = QPrintDialog(self.printer, py_de)
        if printDialog.exec_() == QDialog.Accepted:
            margin = 10
            pageNum = 1
            yPos = 0
            printJob = QPainter()
            printJob.begin(self.printer)
            printJob.setFont(self.font)
            fm = printJob.fontMetrics()

            for i in range(self.textEdit.lines()):
                if margin + yPos > self.printer.height() - margin:
                    pageNum += 1
                    self.printer.newPage()
                    yPos = 0
                printJob.drawText(margin,               # X
                                  margin + yPos,        # Y
                                  self.printer.width(), # Width
                                  self.printer.height(),# Height
                                  QtCore.Qt.AlignTop,       # Alignment
                                  self.textEdit.text(i - 1)# The text to print
                                  )
                yPos += fm.lineSpacing()
            printJob.end

    def saveFile(self):
        fileName = QFileDialog.getSaveFileName()
        f = open(fileName, "w")
        f.write(self.textEdit.text())

    def saveAsFile(self):
        QKeySequence(self.textEdit.trUtf8("Ctrl+Shft+S", "File|Save As"))
        fileName = QFileDialog.getSaveFileName()
        f = open(fileName, "w")
        f.write(self.textEdit.text())

    def goToLine(self):
        maxLine = str(self.textEdit.lines())
        newLineNumber, ok = QInputDialog.getInteger(self.centralwidget,
                                                    "Go to line",
                                                    "Line number: (1, " + maxLine+")")
        if ok:
            newLineNumber -= 1  # Convert from 1-based to 0-based
            self.textEdit.ensureLineVisible(newLineNumber)
            self.textEdit.setCursorPosition(newLineNumber, 0)
            # TODO: Find docs on qscintilla's gotoline(int)
开发者ID:burnchar,项目名称:py-de,代码行数:70,代码来源:py-de.py


注:本文中的PyQt4.QtGui.QPrinter.newPage方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。