def _get_layout_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.pageCollection().page(0).sizeWithUnits().width(), self._c.pageCollection().page(0).sizeWithUnits().height()), QPrinter.Millimeter) p.setFullPage(True) p.setColorMode(QPrinter.Color) p.setResolution(self._c.renderContext().dpi()) 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) exporter = QgsLayoutExporter(self._c) exporter.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_layout_pdf_image call: {0}".format(' '.join(call))) res = False try: subprocess.check_call(call) res = True except subprocess.CalledProcessError as e: qDebug("_get_layout_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
def testPrint(self): l = QgsLayout(QgsProject.instance()) l.initializeDefaults() # add a second page page2 = QgsLayoutItemPage(l) page2.setPageSize('A5') l.pageCollection().addPage(page2) # add some items item1 = QgsLayoutItemShape(l) item1.attemptSetSceneRect(QRectF(10, 20, 100, 150)) fill = QgsSimpleFillSymbolLayer() fill_symbol = QgsFillSymbol() fill_symbol.changeSymbolLayer(0, fill) fill.setColor(Qt.green) fill.setStrokeStyle(Qt.NoPen) item1.setSymbol(fill_symbol) l.addItem(item1) item2 = QgsLayoutItemShape(l) item2.attemptSetSceneRect(QRectF(10, 20, 100, 150)) item2.attemptMove(QgsLayoutPoint(10, 20), page=1) fill = QgsSimpleFillSymbolLayer() fill_symbol = QgsFillSymbol() fill_symbol.changeSymbolLayer(0, fill) fill.setColor(Qt.cyan) fill.setStrokeStyle(Qt.NoPen) item2.setSymbol(fill_symbol) l.addItem(item2) exporter = QgsLayoutExporter(l) # setup settings settings = QgsLayoutExporter.PrintExportSettings() settings.dpi = 80 settings.rasterizeWholeImage = False pdf_file_path = os.path.join(self.basetestpath, 'test_printdpi.pdf') # make a qprinter directed to pdf printer = QPrinter() printer.setOutputFileName(pdf_file_path) printer.setOutputFormat(QPrinter.PdfFormat) self.assertEqual(exporter.print(printer, settings), QgsLayoutExporter.Success) self.assertTrue(os.path.exists(pdf_file_path)) rendered_page_1 = os.path.join(self.basetestpath, 'test_exporttopdfdpi.png') dpi = 80 pdfToPng(pdf_file_path, rendered_page_1, dpi=dpi, page=1) rendered_page_2 = os.path.join(self.basetestpath, 'test_exporttopdfdpi2.png') pdfToPng(pdf_file_path, rendered_page_2, dpi=dpi, page=2) self.assertTrue( self.checkImage('printdpi_page1', 'exporttopdfdpi_page1', rendered_page_1, size_tolerance=1)) self.assertTrue( self.checkImage('printdpi_page2', 'exporttopdfdpi_page2', rendered_page_2, size_tolerance=1))
def export_dock_content(self, output_format: OutputFormats): """ Export the current displayed metadata sheet to the given format. """ layer_name = iface.activeLayer().name() file_path = os.path.join( self.settings.value("UI/lastFileNameWidgetDir"), '{name}.{ext}'.format(name=layer_name, ext=output_format.ext) ) output_file = QFileDialog.getSaveFileName( self, tr("Save File as {format}").format(format=output_format.label), file_path, "{label} (*.{ext})".format( label=output_format.label, ext=output_format.ext, ) ) if output_file[0] == '': return self.settings.setValue("UI/lastFileNameWidgetDir", os.path.dirname(output_file[0])) output_file_path = output_file[0] parent_folder = str(Path(output_file_path).parent) if output_format == OutputFormats.PDF: printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setPageMargins(20, 20, 20, 20, QPrinter.Millimeter) printer.setOutputFileName(output_file_path) self.viewer.print(printer) iface.messageBar().pushSuccess( tr("Export PDF"), tr( "The metadata has been exported as PDF successfully in " "<a href=\"{}\">{}</a>").format(parent_folder, output_file_path) ) elif output_format in [OutputFormats.HTML, OutputFormats.DCAT]: if output_format == OutputFormats.HTML: data_str = self.viewer.page().currentFrame().toHtml() else: sql = self.sql_for_layer( self.current_datasource_uri, output_format=OutputFormats.DCAT) data = self.current_connection.executeSql(sql) with open(resources_path('xml', 'dcat.xml')) as xml_file: xml_template = xml_file.read() locale = QgsSettings().value("locale/userLocale", QLocale().name()) locale = locale.split('_')[0].lower() xml = parseString(xml_template.format(locale=locale, content=data[0][0])) data_str = xml.toprettyxml() with open(output_file[0], "w") as file_writer: file_writer.write(data_str) iface.messageBar().pushSuccess( tr("Export") + ' ' + output_format.label, tr( "The metadata has been exported as {format} successfully in " "<a href=\"{folder}\">{path}</a>").format( format=output_format.label, folder=parent_folder, path=output_file_path) )
def CreatePDF(self, task, out, timestamp, data, frame, rows, columns, fileName, VManager): ''' Create PDF QgsTask ''' font_normal = QFont("Helvetica", 8, QFont.Normal) font_bold = QFont("Helvetica", 9, QFont.Bold) printer = QPrinter(QPrinter.HighResolution) printer.setOutputFormat(QPrinter.PdfFormat) printer.setPageSize(QPrinter.A4) printer.setOutputFileName(out) printer.setFullPage(True) document = QTextDocument() document.setDefaultFont(font_normal) document.setPageSize(printer.paperSize(QPrinter.Point)) cursor = QTextCursor(document) video_t = QCoreApplication.translate("QgsFmvMetadata", "Video : ") time_t = QCoreApplication.translate("QgsFmvMetadata", "TimeStamp : ") cursor.insertHtml(""" <p style='text-align: center;'> <img style='display: block; margin-left: auto; margin-right: auto;' src=\':/imgFMV/images/header_logo.png\' width='200' height='25' /> <p style='text-align: center;'> <strong>%s</strong>%s<strong> <p style='text-align: center;'> <strong>%s</strong>%s <p></p> """ % (video_t, fileName, time_t, timestamp)) tableFormat = QTextTableFormat() tableFormat.setBorderBrush(QBrush(Qt.black)) tableFormat.setAlignment(Qt.AlignHCenter) tableFormat.setHeaderRowCount(1) tableFormat.setCellPadding(2) tableFormat.setCellSpacing(2) cursor.insertTable(rows + 1, columns, tableFormat) tableHeaderFormat = QTextCharFormat() tableHeaderFormat.setFont(font_bold) tableHeaderFormat.setBackground(QColor("#67b03a")) tableHeaderFormat.setForeground(Qt.white) tableHeaderFormat.setVerticalAlignment(QTextCharFormat.AlignMiddle) alternate_background = QTextCharFormat() alternate_background.setBackground(QColor("#DDE9ED")) for column in range(columns): cursor.mergeBlockCharFormat(tableHeaderFormat) cursor.insertText(VManager.horizontalHeaderItem(column).text()) cursor.movePosition(QTextCursor.NextCell) row = 1 for key in sorted(data.keys()): values = [str(key), str(data[key][0]), str(data[key][1])] for column in range(columns): cursor.insertText(values[column]) if (row) % 2 == 0: cursor.mergeBlockCharFormat(alternate_background) cursor.movePosition(QTextCursor.NextCell) row += 1 cursor.movePosition(QTextCursor.End) current_t = QCoreApplication.translate("QgsFmvMetadata", "Current Frame") self.TextBlockCenter(cursor, TextFormat=QTextFormat.PageBreak_AlwaysBefore) cursor.insertHtml(""" <br><p style='text-align: center;'><strong>""" + current_t + """</strong></p><br> """) self.TextBlockCenter(cursor) cursor.insertImage(frame.scaledToWidth(500, Qt.SmoothTransformation)) document.print_(printer) if task.isCanceled(): return None return {'task': task.description()}
def exportLayout(self, cView, folder, title): """Function that sets how to export files.""" currProject = QgsProject.instance() printer = QPrinter() painter = QPainter() exporter = QgsLayoutExporter(cView) # Set page progressbar maximum value self.dlg.pageBar.setValue(0) self.dlg.pageBar.setMaximum(11) # Do the export process if not os.path.exists(os.path.join(folder, title)): os.makedirs(os.path.join(folder, title)) exporter.exportToPdf(os.path.join(folder, title, title + '.pdf'), QgsLayoutExporter.PdfExportSettings()) exporter.exportToImage(os.path.join(folder, title, title + '.jpg'), QgsLayoutExporter.ImageExportSettings()) # read CSV file & load into list with open(os.path.join(self.plugin_dir, "input/metadata_items.csv"), 'r') as metadata_file: reader = csv.reader(metadata_file, delimiter=',') metadata_list = list(reader) settings = ET.Element("mapdoc") mapdata = ET.SubElement(settings, "mapdata") # output fixed QGIS variables to XML """ACTION?""" # output project variables listed in CSV to XML for x in metadata_list[1:]: ma_variable = str(x[0]) elem_name = str(x[1]) elem_name = elem_name.strip() ma_level = str(x[2]) ma_level = ma_level.strip() if (ma_level == 'project') and (elem_name != 'no_xml'): elem_value = str( QgsExpressionContextUtils.projectScope( currProject).variable(ma_variable)) ET.SubElement(mapdata, elem_name).text = elem_value self.dlg.pageBar.setValue(self.dlg.pageBar.value() + 1) if elem_value.strip(): QgsMessageLog.logMessage( ma_variable + ' exported as ' + elem_value, 'MapExport', Qgis.Info) else: msgBar.pushMessage( 'Warning: missing value for ' + ma_variable, 5) QgsMessageLog.logMessage( 'Warning: missing value for ' + ma_variable, 'MapExport') themes = ET.SubElement(mapdata, "themes") for theme in self.dlg.themeBox.findChildren(QCheckBox): if theme.isChecked(): ET.SubElement(themes, 'theme').text = theme.text() for layout in QgsProject.instance().layoutManager().printLayouts(): # Set values of internal variables if layout.name() == self.dlg.layoutSelect.currentText(): date_now = datetime.date.today().strftime("%B %d, %Y") ET.SubElement(mapdata, 'lastUpdated').text = date_now title = layout.name() ET.SubElement(mapdata, 'jpgfilename').text = layout.name() + '.jpg' ET.SubElement(mapdata, 'pdffilename').text = layout.name() + '.pdf' # Action: Which map is selected by this? item = layout.referenceMap() # item = layout.itemById('main') # Get the attr by name and call map_scale = getattr(item, 'scale')() ET.SubElement(mapdata, 'scale').text = str(round(map_scale)) map_extent = item.extent() map_xmin = map_extent.xMinimum() map_xmax = map_extent.xMaximum() map_ymin = map_extent.yMinimum() map_ymax = map_extent.yMaximum() QgsMessageLog.logMessage('Scale ' + str(map_xmin), 'MapExport', Qgis.Info) ET.SubElement(mapdata, 'xmin').text = str(round(map_xmin)) ET.SubElement(mapdata, 'xmax').text = str(round(map_xmax)) ET.SubElement(mapdata, 'ymin').text = str(round(map_ymin)) ET.SubElement(mapdata, 'ymax').text = str(round(map_ymax)) for x in metadata_list[1:]: ma_variable = str(x[0]) elem_name = str(x[1]) elem_name = elem_name.strip() ma_level = str(x[2]) ma_level = ma_level.strip() if ma_level == 'layout': elem_value = str( QgsExpressionContextUtils.layoutScope( layout).variable(ma_variable)) ET.SubElement(mapdata, elem_name).text = elem_value self.dlg.pageBar.setValue(self.dlg.pageBar.value() + 1) if elem_value.strip(): QgsMessageLog.logMessage( ma_variable + ' exported as ' + elem_value, 'MapExport', Qgis.Info) else: msgBar.pushMessage( 'Warning: missing value for ' + ma_variable, 5) QgsMessageLog.logMessage( 'Warning: missing value for ' + ma_variable, 'MapExport') tree = ET.ElementTree(settings) tree.write(os.path.join(folder, title, title + '.xml')) # Set the location and the file name of the zip zippath = os.path.join(folder, title) zf = zipfile.ZipFile( os.path.abspath(folder) + os.sep + title + ".zip", "w") for dirnames, folders, files in os.walk(os.path.join(folder, title)): # for root, dirs, files in os.walk(folder): for file in files: zf.write(os.path.join(os.path.join(folder, title), file), file) zf.close() self.pageProcessed()