本文整理汇总了Python中PyQt4.QtGui.QPrinter.setResolution方法的典型用法代码示例。如果您正苦于以下问题:Python QPrinter.setResolution方法的具体用法?Python QPrinter.setResolution怎么用?Python QPrinter.setResolution使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.QtGui.QPrinter
的用法示例。
在下文中一共展示了QPrinter.setResolution方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: exportPDF
# 需要导入模块: from PyQt4.QtGui import QPrinter [as 别名]
# 或者: from PyQt4.QtGui.QPrinter import setResolution [as 别名]
def exportPDF(self, view, file_name, width, height):
pdf = QPrinter()
pdf.setOutputFormat(QPrinter.PdfFormat)
pdf.setPrintRange(QPrinter.AllPages)
pdf.setOrientation(QPrinter.Portrait)
pdf.setResolution(QPrinter.HighResolution)
pdf.setPaperSize(QSizeF(width, height), QPrinter.Point)
pdf.setFullPage(True)
pdf.setOutputFileName(file_name)
view.mainFrame().print_(pdf)
QApplication.restoreOverrideCursor()
示例2: render_pdf
# 需要导入模块: from PyQt4.QtGui import QPrinter [as 别名]
# 或者: from PyQt4.QtGui.QPrinter import setResolution [as 别名]
def render_pdf(self, page, fileName, paperSize=None):
"""Renders the page into a pdf
:param page: The webpage that we want to render
:param fileName: The path where we want to save the pdf.
For example /home/user/mypdf.pdf
:param paperSize: An PaperSize object that will be used
to render the webpage
"""
mainFrame = page.currentFrame()
printer = QPrinter()
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName(fileName)
printer.setResolution(self._get_default_dpi())
if paperSize is None:
ps = mainFrame.contentsSize()
paperSize = PaperSize(width=ps.width(),
height=ps.width(),
margin=(0, 0, 0, 0),
orientation=None,
page_type=None)
if paperSize.page_type is not None:
if paperSize.orientation.lower() == "landscape":
orientation = QPrinter.Landscape
else:
orientation = QPrinter.Portrait
printer.setOrientation(orientation)
printer.setPaperSize(QPrinter.A4) # Fallback
for f in self.PAGE_TYPE:
if paperSize.page_type.lower() == f[0].lower():
printer.setPaperSize(f[1])
break
else:
sizePt = QSizeF(paperSize.width,
paperSize.height)
printer.setPaperSize(sizePt, QPrinter.Point)
printer.setPageMargins(paperSize.margin[0],
paperSize.margin[1],
paperSize.margin[2],
paperSize.margin[3],
QPrinter.Point)
mainFrame.print_(printer)
示例3: _exportCompositionAsPDF
# 需要导入模块: from PyQt4.QtGui import QPrinter [as 别名]
# 或者: from PyQt4.QtGui.QPrinter import setResolution [as 别名]
def _exportCompositionAsPDF(self,composition,filePath):
"""
Render the composition as a PDF file.
"""
printer = QPrinter()
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName(filePath)
printer.setPaperSize(QSizeF(composition.paperWidth(),composition.paperHeight()),QPrinter.Millimeter)
printer.setFullPage(True)
printer.setColorMode(QPrinter.Color)
printer.setResolution(composition.printResolution())
#Use painter to send output to printer
pdfPainter = QPainter(printer)
paperRectMM = printer.pageRect(QPrinter.Millimeter)
paperRectPixel = printer.pageRect(QPrinter.DevicePixel)
composition.render(pdfPainter,paperRectPixel,paperRectMM)
pdfPainter.end()
示例4: renderPdf
# 需要导入模块: from PyQt4.QtGui import QPrinter [as 别名]
# 或者: from PyQt4.QtGui.QPrinter import setResolution [as 别名]
def renderPdf(self, fileName):
p = QPrinter()
p.setOutputFormat(QPrinter.PdfFormat)
p.setOutputFileName(fileName)
p.setResolution(pdf_dpi)
paperSize = self.m_paperSize
if not len(paperSize):
pageSize = QSize(self.m_page.mainFrame().contentsSize())
paperSize['width'] = str(pageSize.width()) + 'px'
paperSize['height'] = str(pageSize.height()) + 'px'
paperSize['border'] = '0px'
if paperSize.get('width') and paperSize.get('height'):
sizePt = QSizeF(ceil(self.stringToPointSize(paperSize['width'])),
ceil(self.stringToPointSize(paperSize['height'])))
p.setPaperSize(sizePt, QPrinter.Point)
elif 'format' in paperSize:
orientation = QPrinter.Landscape if paperSize.get('orientation') and paperSize['orientation'].lower() == 'landscape' else QPrinter.Portrait
orientation = QPrinter.Orientation(orientation)
p.setOrientation(orientation)
formats = {
'A3': QPrinter.A3,
'A4': QPrinter.A4,
'A5': QPrinter.A5,
'Legal': QPrinter.Legal,
'Letter': QPrinter.Letter,
'Tabloid': QPrinter.Tabloid
}
p.setPaperSize(QPrinter.A4) # fallback
for format, size in formats.items():
if format.lower() == paperSize['format'].lower():
p.setPaperSize(size)
break
else:
return False
border = floor(self.stringToPointSize(paperSize['border'])) if paperSize.get('border') else 0
p.setPageMargins(border, border, border, border, QPrinter.Point)
self.m_page.mainFrame().print_(p)
return True
示例5: renderPdf
# 需要导入模块: from PyQt4.QtGui import QPrinter [as 别名]
# 或者: from PyQt4.QtGui.QPrinter import setResolution [as 别名]
def renderPdf(self, fileName):
p = QPrinter()
p.setOutputFormat(QPrinter.PdfFormat)
p.setOutputFileName(fileName)
p.setResolution(pdf_dpi)
paperSize = self.m_paperSize
if not len(paperSize):
pageSize = QSize(self.m_webPage.mainFrame().contentsSize())
paperSize['width'] = str(pageSize.width()) + 'px'
paperSize['height'] = str(pageSize.height()) + 'px'
paperSize['border'] = '0px'
if paperSize.get('width') and paperSize.get('height'):
sizePt = QSizeF(ceil(self.stringToPointSize(paperSize['width'])),
ceil(self.stringToPointSize(paperSize['height'])))
p.setPaperSize(sizePt, QPrinter.Point)
elif 'format' in paperSize:
orientation = QPrinter.Landscape if paperSize.get('orientation') and paperSize['orientation'].lower() == 'landscape' else QPrinter.Portrait
orientation = QPrinter.Orientation(orientation)
p.setOrientation(orientation)
formats = {
'A0': QPrinter.A0,
'A1': QPrinter.A1,
'A2': QPrinter.A2,
'A3': QPrinter.A3,
'A4': QPrinter.A4,
'A5': QPrinter.A5,
'A6': QPrinter.A6,
'A7': QPrinter.A7,
'A8': QPrinter.A8,
'A9': QPrinter.A9,
'B0': QPrinter.B0,
'B1': QPrinter.B1,
'B2': QPrinter.B2,
'B3': QPrinter.B3,
'B4': QPrinter.B4,
'B5': QPrinter.B5,
'B6': QPrinter.B6,
'B7': QPrinter.B7,
'B8': QPrinter.B8,
'B9': QPrinter.B9,
'B10': QPrinter.B10,
'C5E': QPrinter.C5E,
'Comm10E': QPrinter.Comm10E,
'DLE': QPrinter.DLE,
'Executive': QPrinter.Executive,
'Folio': QPrinter.Folio,
'Ledger': QPrinter.Ledger,
'Legal': QPrinter.Legal,
'Letter': QPrinter.Letter,
'Tabloid': QPrinter.Tabloid
}
p.setPaperSize(QPrinter.A4) # fallback
for format, size in formats.items():
if format.lower() == paperSize['format'].lower():
p.setPaperSize(size)
break
else:
return False
border = floor(self.stringToPointSize(paperSize['border'])) if paperSize.get('border') else 0
p.setPageMargins(border, border, border, border, QPrinter.Point)
self.m_webPage.mainFrame().print_(p)
return True
示例6: BatchPlottingDialog
# 需要导入模块: from PyQt4.QtGui import QPrinter [as 别名]
# 或者: from PyQt4.QtGui.QPrinter import setResolution [as 别名]
#.........这里部分代码省略.........
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)
else:
self.printer.setOrientation(QPrinter.Portrait)
self.printer.setPaperSize(
QSizeF(self.composition.paperWidth(), self.composition.paperHeight()),
QPrinter.Millimeter)
self.printer.setResolution(self.composition.printResolution())
self.composition.beginPrint( self.printer )
painter = QPainter(self.printer)
if not len(atlas.featureFilterErrorString()) == 0:
QMessageBox.warning( self, tr( "Atlas processing error" ),
tr( "Feature filter parser error: %s" % atlas.featureFilterErrorString() ) )
QApplication.restoreOverrideCursor()
return
atlas.beginRender()
progress = QProgressDialog( tr( "Rendering maps..." ), tr( "Abort" ), 0, atlas.numFeatures(), self )
for featureI in range(0, atlas.numFeatures()):
progress.setValue( featureI+1 )
# process input events in order to allow cancelling
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
# start print on a new page if we're not on the first feature
if featureI > 0:
self.printer.newPage()
self.composition.doPrint( self.printer, painter )
atlas.endRender()
painter.end()
示例7: save
# 需要导入模块: from PyQt4.QtGui import QPrinter [as 别名]
# 或者: from PyQt4.QtGui.QPrinter import setResolution [as 别名]
def save(self, imgName, w=None, h=None, header=None, \
dpi=150, take_region=False):
ext = imgName.split(".")[-1].upper()
root = self.startNode
#aspect_ratio = root.fullRegion.height() / root.fullRegion.width()
aspect_ratio = self.i_height / self.i_width
# auto adjust size
if w is None and h is None and (ext == "PDF" or ext == "PS"):
w = dpi * 6.4
h = w * aspect_ratio
if h>dpi * 11:
h = dpi * 11
w = h / aspect_ratio
elif w is None and h is None:
w = self.i_width
h = self.i_height
elif h is None :
h = w * aspect_ratio
elif w is None:
w = h / aspect_ratio
if ext == "SVG":
svg = QtSvg.QSvgGenerator()
svg.setFileName(imgName)
svg.setSize(QtCore.QSize(w, h))
svg.setViewBox(QtCore.QRect(0, 0, w, h))
#svg.setTitle("SVG Generator Example Drawing")
#svg.setDescription("An SVG drawing created by the SVG Generator")
pp = QtGui.QPainter()
pp.begin(svg)
targetRect = QtCore.QRectF(0, 0, w, h)
self.render(pp, targetRect, self.sceneRect())
pp.end()
elif ext == "PDF" or ext == "PS":
format = QPrinter.PostScriptFormat if ext == "PS" else QPrinter.PdfFormat
printer = QPrinter(QPrinter.HighResolution)
printer.setResolution(dpi)
printer.setOutputFormat(format)
printer.setPageSize(QPrinter.A4)
pageTopLeft = printer.pageRect().topLeft()
paperTopLeft = printer.paperRect().topLeft()
# For PS -> problems with margins
# print paperTopLeft.x(), paperTopLeft.y()
# print pageTopLeft.x(), pageTopLeft.y()
# print printer.paperRect().height(), printer.pageRect().height()
topleft = pageTopLeft - paperTopLeft
printer.setFullPage(True);
printer.setOutputFileName(imgName);
pp = QtGui.QPainter(printer)
if header:
pp.setFont(QtGui.QFont("Verdana",12))
pp.drawText(topleft.x(),20, header)
targetRect = QtCore.QRectF(topleft.x(), 20 + (topleft.y()*2), w, h)
else:
targetRect = QtCore.QRectF(topleft.x(), topleft.y()*2, w, h)
if take_region:
self.selector.setVisible(False)
self.render(pp, targetRect, self.selector.rect())
self.selector.setVisible(True)
else:
self.render(pp, targetRect, self.sceneRect())
pp.end()
return
else:
targetRect = QtCore.QRectF(0, 0, w, h)
ii= QtGui.QImage(w, \
h, \
QtGui.QImage.Format_ARGB32)
pp = QtGui.QPainter(ii)
pp.setRenderHint(QtGui.QPainter.Antialiasing )
pp.setRenderHint(QtGui.QPainter.TextAntialiasing)
pp.setRenderHint(QtGui.QPainter.SmoothPixmapTransform)
if take_region:
self.selector.setVisible(False)
self.render(pp, targetRect, self.selector.rect())
self.selector.setVisible(True)
else:
self.render(pp, targetRect, self.sceneRect())
pp.end()
ii.save(imgName)
示例8: Printer
# 需要导入模块: from PyQt4.QtGui import QPrinter [as 别名]
# 或者: from PyQt4.QtGui.QPrinter import setResolution [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)
#.........这里部分代码省略.........
示例9: export_all_features
# 需要导入模块: from PyQt4.QtGui import QPrinter [as 别名]
# 或者: from PyQt4.QtGui.QPrinter import setResolution [as 别名]
#.........这里部分代码省略.........
else:
new_width = old_ratio * new_ext.height()
delta_width = new_width - new_ext.width()
new_ext.setXMinimum(bbox.xMinimum() - delta_width / 2)
new_ext.setXMaximum(bbox.xMaximum() + delta_width / 2)
if VRP_DEBUG is True: QgsMessageLog.logMessage(u'bbox old:{0}'.format(compmap.extent().toString()), DLG_CAPTION)
compmap.setNewExtent(new_ext)
if VRP_DEBUG is True: QgsMessageLog.logMessage(u'bbox new:{0}'.format(compmap.extent().toString()), DLG_CAPTION)
#round up to next 1000
compmap.setNewScale(math.ceil((compmap.scale()/1000.0)) * 1000.0)
if VRP_DEBUG is True: QgsMessageLog.logMessage(u'bbox new (after scale):{0}'.format(compmap.extent().toString()), DLG_CAPTION)
#add ORTHO after new extent -> performance
if not self.ortho is None:
self.ortho_lyr = self.__add_raster_layer(self.ortho, self.lyrname_ortho)
self.__reorder_layers()
self.comp_leg = self.__get_items(QgsComposerLegend)
self.comp_lbl = self.__get_items(QgsComposerLabel)
self.__update_composer_items(self.settings.dkm_gemeinde(self.gem_name)['lyrnamegstk'])
if VRP_DEBUG is True:
QgsMessageLog.logMessage(u'paperWidth:{0} paperHeight:{1}'.format(composition.paperWidth(), composition.paperHeight()), DLG_CAPTION)
printer = QPrinter()
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])
示例10: _get_composer_pdf_image
# 需要导入模块: from PyQt4.QtGui import QPrinter [as 别名]
# 或者: from PyQt4.QtGui.QPrinter import setResolution [as 别名]
def _get_composer_pdf_image(self, width, height, dpi):
pdfpath = getTempfilePath('pdf')
temp_size = os.path.getsize(pdfpath)
p = QPrinter()
p.setOutputFormat(QPrinter.PdfFormat)
p.setOutputFileName(pdfpath)
p.setPaperSize(QSizeF(self._c.paperWidth(), self._c.paperHeight()),
QPrinter.Millimeter)
p.setFullPage(True)
p.setColorMode(QPrinter.Color)
p.setResolution(self._c.printResolution())
pdf_p = QPainter(p)
# page_mm = p.pageRect(QPrinter.Millimeter)
# page_px = p.pageRect(QPrinter.DevicePixel)
# self._c.render(pdf_p, page_px, page_mm)
self._c.renderPage(pdf_p, 0)
pdf_p.end()
if temp_size == os.path.getsize(pdfpath):
return False, ''
filepath = getTempfilePath('png')
# Poppler (pdftocairo or pdftoppm):
# PDFUTIL -png -singlefile -r 72 -x 0 -y 0 -W 420 -H 280 in.pdf pngbase
# muPDF (mudraw):
# PDFUTIL -c rgb[a] -r 72 -w 420 -h 280 -o out.png in.pdf
if PDFUTIL.strip().endswith('pdftocairo'):
filebase = os.path.join(
os.path.dirname(filepath),
os.path.splitext(os.path.basename(filepath))[0]
)
call = [
PDFUTIL, '-png', '-singlefile', '-r', str(dpi),
'-x', '0', '-y', '0', '-W', str(width), '-H', str(height),
pdfpath, filebase
]
elif PDFUTIL.strip().endswith('mudraw'):
call = [
PDFUTIL, '-c', 'rgba',
'-r', str(dpi), '-w', str(width), '-h', str(height),
# '-b', '8',
'-o', filepath, pdfpath
]
else:
return False, ''
qDebug("_get_composer_pdf_image call: {0}".format(' '.join(call)))
res = False
try:
subprocess.check_call(call)
res = True
except subprocess.CalledProcessError as e:
qDebug("_get_composer_pdf_image failed!\n"
"cmd: {0}\n"
"returncode: {1}\n"
"message: {2}".format(e.cmd, e.returncode, e.message))
if not res:
os.unlink(filepath)
filepath = ''
return res, filepath
示例11: QPrinter
# 需要导入模块: from PyQt4.QtGui import QPrinter [as 别名]
# 或者: from PyQt4.QtGui.QPrinter import setResolution [as 别名]
compmap.setPreviewMode(QgsComposerMap.Render)
#compmap.updateItem()
#emit compmap.itemChanged();
#compmap.extentChanged();
#compmap.toggleAtlasPreview()
#compmap.setNewScale(compmap.scale()+1)
#c.setPrintResolution(150)
#print c.printResolution()
c.setPrintAsRaster(False)
printer = QPrinter()
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName(pdf_out)
printer.setPaperSize(QSizeF(c.paperWidth(), c.paperHeight()), QPrinter.Millimeter)
printer.setFullPage(True)
printer.setColorMode(QPrinter.Color)
printer.setResolution(c.printResolution())
pdfPainter = QPainter(printer)
paperRectMM = printer.pageRect(QPrinter.Millimeter)
paperRectPixel = printer.pageRect(QPrinter.DevicePixel)
QgsPaintEngineHack.fixEngineFlags(printer.paintEngine())
#c.renderPage(pdfPainter, 0)
c.doPrint(printer,pdfPainter)
pdfPainter.end()
subprocess.call(('xdg-open', pdf_out))
print 'FERTIG'
示例12: renderPdf
# 需要导入模块: from PyQt4.QtGui import QPrinter [as 别名]
# 或者: from PyQt4.QtGui.QPrinter import setResolution [as 别名]
def renderPdf(self, fileName):
p = QPrinter()
p.setOutputFormat(QPrinter.PdfFormat)
p.setOutputFileName(fileName)
p.setResolution(self.pdf_dpi)
paperSize = self.m_paperSize
if not len(paperSize):
pageSize = QSize(self.m_webPage.mainFrame().contentsSize())
paperSize["width"] = str(pageSize.width()) + "px"
paperSize["height"] = str(pageSize.height()) + "px"
paperSize["border"] = "0px"
if paperSize.get("width") and paperSize.get("height"):
sizePt = QSizeF(
ceil(self.stringToPointSize(paperSize["width"])), ceil(self.stringToPointSize(paperSize["height"]))
)
p.setPaperSize(sizePt, QPrinter.Point)
elif "format" in paperSize:
orientation = (
QPrinter.Landscape
if paperSize.get("orientation") and paperSize["orientation"].lower() == "landscape"
else QPrinter.Portrait
)
orientation = QPrinter.Orientation(orientation)
p.setOrientation(orientation)
formats = {
"A0": QPrinter.A0,
"A1": QPrinter.A1,
"A2": QPrinter.A2,
"A3": QPrinter.A3,
"A4": QPrinter.A4,
"A5": QPrinter.A5,
"A6": QPrinter.A6,
"A7": QPrinter.A7,
"A8": QPrinter.A8,
"A9": QPrinter.A9,
"B0": QPrinter.B0,
"B1": QPrinter.B1,
"B2": QPrinter.B2,
"B3": QPrinter.B3,
"B4": QPrinter.B4,
"B5": QPrinter.B5,
"B6": QPrinter.B6,
"B7": QPrinter.B7,
"B8": QPrinter.B8,
"B9": QPrinter.B9,
"B10": QPrinter.B10,
"C5E": QPrinter.C5E,
"Comm10E": QPrinter.Comm10E,
"DLE": QPrinter.DLE,
"Executive": QPrinter.Executive,
"Folio": QPrinter.Folio,
"Ledger": QPrinter.Ledger,
"Legal": QPrinter.Legal,
"Letter": QPrinter.Letter,
"Tabloid": QPrinter.Tabloid,
}
p.setPaperSize(QPrinter.A4) # fallback
for format_, size in formats.items():
if format_.lower() == paperSize["format"].lower():
p.setPaperSize(size)
break
else:
return False
border = floor(self.stringToPointSize(paperSize["border"])) if paperSize.get("border") else 0
p.setPageMargins(border, border, border, border, QPrinter.Point)
self.m_webPage.mainFrame().print_(p)
return True