def readData(self, data): """Restore saved settings from a dictionary. Arguments: data -- a dictionary of stored non-default settings """ self.setDefaults() # necessary for undo/redo self.drawLines = data.get('printlines', True) self.widowControl = data.get('printwidowcontrol', True) self.indentFactor = data.get('printindentfactor', 2.0) if 'printpapersize' in data: self.pageLayout.setPageSize( QPageSize(getattr(QPageSize, data['printpapersize']))) self.pageLayout.setMargins(QMarginsF(*(_defaultMargin, ) * 4)) if 'printpaperwidth' in data and 'printpaperheight' in data: width = data['printpaperwidth'] height = data['printpaperheight'] self.pageLayout.setPageSize( QPageSize(QSizeF(width, height), QPageSize.Inch)) self.pageLayout.setMargins(QMarginsF(*(_defaultMargin, ) * 4)) if not data.get('printportrait', True): self.pageLayout.setOrientation(QPageLayout.Landscape) if 'printmargins' in data: margins = data['printmargins'] self.pageLayout.setMargins(QMarginsF(*margins)) self.headerMargin = data.get('printheadermargin', _defaultHeaderPos) self.footerMargin = data.get('printfootermargin', _defaultHeaderPos) self.numColumns = data.get('printnumcolumns', 1) self.columnSpacing = data.get('printcolumnspace', _defaultColumnSpace) self.headerText = data.get('printheadertext', '') self.footerText = data.get('printfootertext', '') if 'printfont' in data: self.useDefaultFont = False self.mainFont.fromString(data['printfont']) self.adjustSpacing()
def saveAsPdf(self, path): pdf = QPrinter() pdf.setFullPage(True) pdf.setOutputFileName(str(path)) first = True painter = QPainter() for source in self.images: marked = source.copy() self.paintOn(marked) pdf.setPageSize(QPageSize(marked.size())) if first: first = False painter.begin(pdf) else: pdf.newPage() # though we set page size, the rect is not the same rect = marked.rect() rect.setWidth(pdf.width()) rect.setHeight(pdf.height()) painter.drawImage(rect, marked) painter.end()
def pdf(self, filename, rect=None, resolution=72.0, paperColor=None): """Create a PDF file for the selected rect or the whole page. The filename may be a string or a QIODevice object. The rectangle is relative to our top-left position. Normally vector graphics are rendered, but in cases where that is not possible, the resolution will be used to determine the DPI for the generated rendering. """ # map to the original page source = self.pageRect() if rect is None else self.mapFromPage().rect( rect) # scale to target size w = source.width() * self.scaleX h = source.height() * self.scaleY if self.computedRotation & 1: w, h = h, w targetSize = QSizeF(w, h) pdf = QPdfWriter(filename) pdf.setCreator("qpageview") pdf.setResolution(int(resolution)) layout = pdf.pageLayout() layout.setMode(layout.FullPageMode) layout.setPageSize( QPageSize(targetSize * 72.0 / self.dpi, QPageSize.Point)) pdf.setPageLayout(layout) return self.output(pdf, source, paperColor)
def exportPDF(self): """ Opens a dialog to export the tree as pdf. Saves the tree to the declared location :return: True if saving was successful """ self.mouse() dialog = QFileDialog() fileName = dialog.getSaveFileName(self, 'Export as PDF', '', 'PDF (*.pdf)') if fileName != ('', ''): self.scene.clearSelection() try: printer = QPrinter(QPrinter.HighResolution) printer.setOutputFormat(QPrinter.PdfFormat) printer.setPageSize(QPageSize(self.scene.itemsBoundingRect().size(), QPageSize.Point)) printer.setOutputFileName(fileName[0]) p = QPainter() if p.begin(printer) is False: raise Exception('Error starting painter') self.scene.setSceneRect(self.scene.itemsBoundingRect()) self.graphicsView.setScene(self.scene) self.graphicsView.update() self.scene.render(p) p.end() self.scene.setSceneRect(QRectF(None)) except Exception as e: MessageBox('Error while saving to pdf', str(e)) return False return True return False
def pdf(filename, pageList, resolution=72, paperColor=None): """Export the pages in pageList to a PDF document. filename can be a string or any QIODevice. Normally vector graphics are rendered, but in cases where that is not possible, the resolution will be used to determine the DPI for the generated rendering. The computedRotation attribute of the pages is used to determine the rotation. Make copies of the pages if you run this function in a background thread. """ pdf = QPdfWriter(filename) pdf.setCreator("qpageview") pdf.setResolution(resolution) for n, page in enumerate(pageList): # map to the original page source = page.pageRect() # scale to target size w = source.width() * page.scaleX h = source.height() * page.scaleY if page.computedRotation & 1: w, h = h, w targetSize = QSizeF(w, h) if n: pdf.newPage() layout = pdf.pageLayout() layout.setMode(layout.FullPageMode) layout.setPageSize( QPageSize(targetSize * 72.0 / page.dpi, QPageSize.Point)) pdf.setPageLayout(layout) # TODO handle errors? page.output(pdf, source, paperColor)
def printPDF(url, margins): app = QtWidgets.QApplication(sys.argv) loader = QtWebEngineWidgets.QWebEngineView() loader.setZoomFactor(1) loader.load(QtCore.QUrl(url)) layout = QPageLayout( QPageSize(QPageSize.A4), QPageLayout.Portrait, QMarginsF(margins[0], margins[1], margins[2], margins[3])) def printFinished(): page = loader.page() page.profile().clearHttpCache() log("%s Printing Finished!" % page.title()) app.exit() def printToPDF(finished): loader.show() page = loader.page() page.printToPdf("./pdfs/%s.pdf" % page.title(), layout) loader.page().pdfPrintingFinished.connect(printFinished) loader.loadFinished.connect(printToPDF) app.exec_()
def __init__(self, filePath, parent=None): """ Constructor @param filePath path of the file to write into @type str @param parent reference to the parent widget @type QWidget """ super(PrintToPdfDialog, self).__init__(parent) self.setupUi(self) self.pdfFilePicker.setMode(E5PathPickerModes.SaveFileOverwriteMode) self.pdfFilePicker.setFilters( self.tr("PDF Files (*.pdf);;" "All Files (*)")) if not os.path.isabs(filePath): documentsPath = QStandardPaths.writableLocation( QStandardPaths.DocumentsLocation) if documentsPath: filePath = os.path.join(documentsPath, filePath) else: filePath = os.path.abspath(filePath) self.pdfFilePicker.setText(filePath, toNative=True) self.__currentPageLayout = QPageLayout(QPageSize(QPageSize.A4), QPageLayout.Portrait, QMarginsF(0.0, 0.0, 0.0, 0.0)) self.__updatePageLayoutLabel()
def get_painter(self, printer) -> QPainter: layout = QPageLayout() layout.setPageSize(QPageSize(QPageSize.A4)) layout.setOrientation(QPageLayout.Portrait) printer.setPageLayout(layout) printer.setResolution(self.resolution) painter = QPainter() self.painter = painter return painter
def load_finished(self): if self.do_preview: self.show() else: pageLayout = QPageLayout(QPageSize(QPageSize.A5), QPageLayout.Portrait, QMarginsF(0, 0, 0, 0)) self.page().printToPdf(self.filename, pageLayout) self.page().pdfPrintingFinished.connect(on_pdf_finished)
def loadFinished(self, ok): if ok: self.status_bar.showMessage("Printing PDF") self.page.printToPdf(self.filename, pageLayout=QPageLayout( QPageSize(QPageSize.A5), QPageLayout.Portrait, QMarginsF(30.0, 30.0, 30.0, 30.0))) else: self.status_bar.showMessage("There was an error printing the PDF")
def __post_init__(self): # Scaling ratio for Qt point 72dpi -> constants.PRINT_DPI ratio = 72 / constants.PRINT_DPI super().__setattr__( "qt_object", QPageLayout( QPageSize( QSize( int(self.width.base_value * ratio), int(self.height.base_value * ratio), ), ), QPageLayout.Portrait, # Margins are implemented at a higher level QMarginsF(0, 0, 0, 0), ), )
def setDefaults(self): """Set all paparmeters saved in TreeLine files to default values. """ self.drawLines = True self.widowControl = True self.indentFactor = 2.0 self.pageLayout.setUnits(QPageLayout.Inch) self.pageLayout.setPageSize(QPageSize(QPageSize.Letter)) self.pageLayout.setOrientation(QPageLayout.Portrait) self.pageLayout.setMargins(QMarginsF(*(_defaultMargin, ) * 4)) self.headerMargin = _defaultHeaderPos self.footerMargin = _defaultHeaderPos self.numColumns = 1 self.columnSpacing = _defaultColumnSpace self.headerText = '' self.footerText = '' self.useDefaultFont = True self.setDefaultFont()
def paperSizeName(self, sizeId=None): """Return a QPageSize attribute name matching the paper size ID. Arguments: sizeId -- the Qt size ID, if None, use current size """ if sizeId == None: sizeId = self.pageLayout.pageSize().id() matches = [] for name, num in vars(QPageSize).items(): if num == sizeId: matches.append(name) if not matches: return 'Custom' if len(matches) > 1: text = QPageSize(sizeId).name().split(None, 1)[0] for name in matches: if name == text: return name return matches[0]
def generate_pdf(df_data): app = QtWidgets.QApplication(sys.argv) list_globalid = list(set(df_data['Global ID'].to_list())) print(list_globalid) for gid in list_globalid: html_file = 'P' + str(gid) + '.html' df_temp = df_data[df_data['Global ID'] == gid] df_temp.columns = set_columns() th_props = [('font-size', '8px'), ('text-align', 'center'), ('font-weight', 'bold'), ('color', '#6d6d6d'), ('background-color', '#f7f7f9')] td_props = [('font-size', '8px')] pd.set_option('colheader_justify', 'center') # FOR TABLE <th> df_temp.to_html(html_file, index=False, justify='left', border="1") loader = QtWebEngineWidgets.QWebEngineView() loader.load(QtCore.QUrl(get_path() + html_file)) layout = QPageLayout(QPageSize(QPageSize.A4), QPageLayout.Portrait, QMarginsF(8, 12, 8, 12)) def printFinished(): page = loader.page() # print("%s Printing Finished!" % page.title()) app.exit() def printToPDF(finished): loader.show() page = loader.page() page.printToPdf("%s.pdf" % page.title()[:9], layout) print("Generated pdf file %s.pdf" % page.title()[:9]) loader.page().pdfPrintingFinished.connect(printFinished) loader.loadFinished.connect(printToPDF) app.exec_() loader.close() app.closeAllWindows()
def savePdf(self): fileName = QFileDialog.getSaveFileName(self, self.tr("Export document to PDF"), self.currentTab.getBaseName() + ".pdf", self.tr("PDF files (*.pdf)"))[0] if fileName: if not QFileInfo(fileName).suffix(): fileName += ".pdf" title, htmltext, preview = self.currentTab.getDocumentForExport() if globalSettings.useWebEngine and hasattr(preview.page(), "printToPdf"): pageSize = self.getPageSizeByName(globalSettings.paperSize) if pageSize is None: pageSize = QPageSize(QPageSize.A4) margins = QMarginsF(20, 20, 13, 20) # left, top, right, bottom (in millimeters) layout = QPageLayout(pageSize, QPageLayout.Portrait, margins, QPageLayout.Millimeter) preview.page().printToPdf(fileName, layout) # Available since Qt 5.7 return printer = self.standardPrinter(title) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(fileName) document = self.getDocumentForPrint(title, htmltext, preview) if document != None: document.print(printer)