void MultiLayer::exportToEPS(const QString& fname, int res, QPrinter::Orientation o, QPrinter::PageSize pageSize, QPrinter::ColorMode col) { QPrinter printer; printer.setResolution(res); printer.setPageSize(pageSize); printer.setColorMode(col); printer.setOrientation(o); printer.setFullPage(TRUE); printer.setOutputToFile (TRUE); printer.setOutputFileName(fname); QPainter paint(&printer); QPaintDeviceMetrics pdmTo(&printer); int dpiy = pdmTo.logicalDpiY(); int margin = (int) ( (0.5/2.54)*dpiy ); // 5 mm margins QSize size = canvas->size(); double scaleFactorX=(double)(pdmTo.width() - 2*margin)/(double)size.width(); double scaleFactorY=(double)(pdmTo.height() - 2*margin)/(double)size.height(); for (int i=0;i<(int)graphsList->count();i++) { Graph *gr=(Graph *)graphsList->at(i); Plot *myPlot= (Plot *)gr->plotWidget(); PrintFilter filter(myPlot); filter.setOptions(QwtPlotPrintFilter::PrintAll | QwtPlotPrintFilter::PrintTitle | QwtPlotPrintFilter::PrintCanvasBackground); QPoint pos=gr->pos(); pos=QPoint(int(margin + pos.x()*scaleFactorX),int(margin + pos.y()*scaleFactorY)); int width=int(myPlot->frameGeometry().width()*scaleFactorX); int height=int(myPlot->frameGeometry().height()*scaleFactorY); QRect rect = QRect(pos,QSize(width,height)); if (myPlot->paletteBackgroundColor() != QColor(white)) paint.fillRect(rect, myPlot->paletteBackgroundColor()); int lw = myPlot->lineWidth(); if ( lw > 0) { myPlot->printFrame(&paint, rect); rect.moveBy ( lw, lw); rect.setWidth(rect.width() - 2*lw); rect.setHeight(rect.height() - 2*lw); } myPlot->print(&paint, rect, filter); } if (hasOverlapingLayers()) updateTransparency(); }
void Matrix::exportVector(const QString& fileName, int res, bool color) { if ( fileName.isEmpty() ){ QMessageBox::critical(this, tr("QtiPlot - Error"), tr("Please provide a valid file name!")); return; } QPrinter printer; printer.setCreator("QtiPlot"); printer.setFullPage(true); if (res) printer.setResolution(res); printer.setOutputFileName(fileName); if (fileName.contains(".eps")) printer.setOutputFormat(QPrinter::PostScriptFormat); if (color) printer.setColorMode(QPrinter::Color); else printer.setColorMode(QPrinter::GrayScale); printer.setOrientation(QPrinter::Portrait); int cols = numCols(); int rows = numRows(); QRect rect = QRect(0, 0, cols, rows); printer.setPaperSize(QSizeF(cols, rows), QPrinter::DevicePixel); QPainter paint(&printer); paint.drawImage(rect, d_matrix_model->renderImage()); paint.end(); }
void QgsComposition::beginPrint( QPrinter &printer ) { //set resolution based on composer setting printer.setFullPage( true ); printer.setColorMode( QPrinter::Color ); //set user-defined resolution printer.setResolution( printResolution() ); }
void SchedulePrintDialog::setupPdfPrinter( QPrinter & printer ) { printer.setOutputFormat( QPrinter::PdfFormat ); setupPrinter(printer); printer.setFullPage( true ); printer.setResolution( mDpiSpin->value() ); printer.setFontEmbeddingEnabled(false); }
void OpenInfraPlatform::UserInterface::Alignment2DScene::exportToFile(QWidget* parent) { QString filter; QString fn = QFileDialog::getSaveFileName(parent, tr("Save Vertical Alignment as..."), QString(), tr("PNG File (*.png);; JPG File (*.jpg);; PDF File (*.pdf);; SVG File (*.svg)"), &filter); if(fn.isEmpty()) return; if(filter == "PNG File (*.png)" || filter == "JPG File (*.jpg)") { QImage image(sceneRect().size().toSize(), QImage::Format::Format_ARGB32); image.fill(Qt::darkGray); QPainter painter(&image); painter.setRenderHints(QPainter::Antialiasing); render(&painter); image.save(fn); } else { QPrinter printer; QSvgGenerator svgGen; QPaintDevice* device; if(filter == "PDF File (*.pdf)") { printer.setResolution(QPrinter::HighResolution); printer.setPageSize( QPrinter::A4 ); printer.setOrientation( QPrinter::Landscape ); printer.setOutputFormat( QPrinter::PdfFormat ); printer.setOutputFileName(fn); device = &printer; } else if(filter == "SVG File (*.svg)") { QRectF rect = sceneRect(); svgGen.setFileName(fn); svgGen.setSize(QSize(rect.width(),rect.height())); svgGen.setViewBox(QRect(0,0,rect.width(),rect.height())); svgGen.setTitle("Vertical Alignment"); device = &svgGen; } else { return; } QPainter painter(device); configureColors(A2D_DrawState::A2D_Print); render(&painter); configureColors(A2D_DrawState::A2D_Draw); } }
void UBExportFullPDF::saveOverlayPdf(UBDocumentProxy* pDocumentProxy, const QString& filename) { if (!pDocumentProxy || filename.length() == 0 || pDocumentProxy->pageCount() == 0) return; //PDF qDebug() << "exporting document to PDF Merger" << filename; QPrinter pdfPrinter; pdfPrinter.setOutputFormat(QPrinter::PdfFormat); pdfPrinter.setResolution(UBSettings::settings()->pdfResolution->get().toInt()); pdfPrinter.setOutputFileName(filename); pdfPrinter.setFullPage(true); QPainter* pdfPainter = 0; for(int pageIndex = 0 ; pageIndex < pDocumentProxy->pageCount(); pageIndex++) { UBGraphicsScene* scene = UBPersistenceManager::persistenceManager()->loadDocumentScene(pDocumentProxy, pageIndex); // set background to white, no grid for PDF output bool isDark = scene->isDarkBackground(); bool isCrossed = scene->isCrossedBackground(); scene->setBackground(false, false); // set high res rendering scene->setRenderingQuality(UBItem::RenderingQualityHigh); scene->setRenderingContext(UBGraphicsScene::PdfExport); QSize pageSize = scene->nominalSize(); UBGraphicsPDFItem *pdfItem = qgraphicsitem_cast<UBGraphicsPDFItem*>(scene->backgroundObject()); if (pdfItem) mHasPDFBackgrounds = true; pdfPrinter.setPaperSize(QSizeF(pageSize.width()*mScaleFactor, pageSize.height()*mScaleFactor), QPrinter::Point); if (!pdfPainter) pdfPainter = new QPainter(&pdfPrinter); if (pageIndex != 0) pdfPrinter.newPage(); //render to PDF scene->setDrawingMode(true); scene->render(pdfPainter, QRectF(), scene->normalizedSceneRect()); //restore screen rendering quality scene->setRenderingContext(UBGraphicsScene::Screen); scene->setRenderingQuality(UBItem::RenderingQualityNormal); //restore background state scene->setDrawingMode(false); scene->setBackground(isDark, isCrossed); } if (pdfPainter) delete pdfPainter; }
bool UBExportPDF::persistsDocument(UBDocumentProxy* pDocumentProxy, const QString& filename) { QPrinter pdfPrinter; qDebug() << "exporting document to PDF" << filename; pdfPrinter.setOutputFormat(QPrinter::PdfFormat); pdfPrinter.setResolution(UBSettings::settings()->pdfResolution->get().toInt()); pdfPrinter.setOutputFileName(filename); pdfPrinter.setFullPage(true); //need to calculate screen resolution QDesktopWidget* desktop = UBApplication::desktop(); int dpiCommon = (desktop->physicalDpiX() + desktop->physicalDpiY()) / 2; float scaleFactor = 72.0f / dpiCommon; QPainter pdfPainter; bool painterNeedsBegin = true; int existingPageCount = pDocumentProxy->pageCount(); for(int pageIndex = 0 ; pageIndex < existingPageCount; pageIndex++) { UBGraphicsScene* scene = UBPersistenceManager::persistenceManager()->loadDocumentScene(pDocumentProxy, pageIndex); UBApplication::showMessage(tr("Exporting page %1 of %2").arg(pageIndex + 1).arg(existingPageCount)); // set background to white, no crossing for PDF output bool isDark = scene->isDarkBackground(); bool isCrossed = scene->isCrossedBackground(); scene->setBackground(false, false); QSize pageSize = scene->nominalSize(); // set high res rendering scene->setRenderingQuality(UBItem::RenderingQualityHigh); scene->setRenderingContext(UBGraphicsScene::NonScreen); //setting page size to appropriate value pdfPrinter.setPaperSize(QSizeF(pageSize.width()*scaleFactor, pageSize.height()*scaleFactor), QPrinter::Point); if(painterNeedsBegin) painterNeedsBegin = !pdfPainter.begin(&pdfPrinter); //render to PDF scene->render(&pdfPainter, QRectF(), scene->normalizedSceneRect()); if (pageIndex < existingPageCount - 1) pdfPrinter.newPage(); //restore screen rendering quality scene->setRenderingContext(UBGraphicsScene::Screen); scene->setRenderingQuality(UBItem::RenderingQualityNormal); //restore background state scene->setBackground(isDark, isCrossed); } if(!painterNeedsBegin) pdfPainter.end(); return true; }
bool Phantom::renderPdf(const QString &fileName) { QPrinter printer; printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(fileName); printer.setResolution(PHANTOMJS_PDF_DPI); QVariantMap paperSize = m_paperSize; if (paperSize.isEmpty()) { const QSize pageSize = m_page.mainFrame()->contentsSize(); paperSize.insert("width", QString::number(pageSize.width()) + "px"); paperSize.insert("height", QString::number(pageSize.height()) + "px"); paperSize.insert("border", "0px"); } if (paperSize.contains("width") && paperSize.contains("height")) { const QSizeF sizePt(ceil(stringToPointSize(paperSize.value("width").toString())), ceil(stringToPointSize(paperSize.value("height").toString()))); printer.setPaperSize(sizePt, QPrinter::Point); } else if (paperSize.contains("format")) { const QPrinter::Orientation orientation = paperSize.contains("orientation") && paperSize.value("orientation").toString().compare("landscape", Qt::CaseInsensitive) == 0 ? QPrinter::Landscape : QPrinter::Portrait; printer.setOrientation(orientation); static const struct { QString format; QPrinter::PaperSize paperSize; } formats[] = { { "A3", QPrinter::A3 }, { "A4", QPrinter::A4 }, { "A5", QPrinter::A5 }, { "Legal", QPrinter::Legal }, { "Letter", QPrinter::Letter }, { "Tabloid", QPrinter::Tabloid } }; printer.setPaperSize(QPrinter::A4); // Fallback for (uint i = 0; i < sizeof(formats) / sizeof(formats[0]); ++i) { if (paperSize.value("format").toString().compare(formats[i].format, Qt::CaseInsensitive) == 0) { printer.setPaperSize(formats[i].paperSize); break; } } } else { return false; } const qreal border = paperSize.contains("border") ? floor(stringToPointSize(paperSize.value("border").toString())) : 0; printer.setPageMargins(border, border, border, border, QPrinter::Point); m_page.mainFrame()->print(&printer); return true; }
void MainWindow::on_actionPrint_triggered(bool) { //no nothing without images if (images_.count()==0) return; QPrinter printer; printer.setResolution(180); printer.setPaperSize(QPrinter::A4); printer.setOrientation(QPrinter::Portrait); QPrintPreviewDialog dlg(&printer, this); dlg.setWindowFlags ( Qt::Window ); connect(&dlg, SIGNAL(paintRequested(QPrinter*)), SLOT(printPreview(QPrinter *))); if(dlg.exec() == QDialog::Rejected) return; }
void MultiLayer::print() { QPrinter printer; printer.setResolution(84); printer.setOrientation(QPrinter::Landscape); printer.setColorMode (QPrinter::Color); printer.setFullPage(TRUE); if (printer.setup()) { QPainter paint(&printer); printAllLayers(&paint); paint.end(); } }
void MSPeaksWnd::handlePrintCurrentView( const QString& pdfname ) { // A4 := 210mm x 297mm (8.27 x 11.69 inch) QSizeF sizeMM( 260, 160 ); // 260x160mm int resolution = 300; const double mmToInch = 1.0 / 25.4; const QSizeF size = sizeMM * mmToInch * resolution; double margin_left = 0.2 /* inch */ * resolution; //double margin_right = ( 8.27 - 0.2 ) * resolution; //double margin_center = (margin_right - margin_left) / 2 + margin_left; QPrinter printer; printer.setColorMode( QPrinter::Color ); printer.setPaperSize( QPrinter::A4 ); printer.setFullPage( false ); printer.setOrientation( QPrinter::Landscape ); printer.setDocName( "QtPlatz MS Peaks" ); printer.setOutputFileName( pdfname ); printer.setResolution( resolution ); //-------------------- QPainter painter( &printer ); int n = 0; for ( auto& plot: plots_ ) { QRectF boundingRect; QRectF drawRect( margin_left, 0.0, printer.width() / 2.0, printer.height() ); if ( n++ & 01 ) { drawRect.moveLeft( printer.width() / 2.0 ); painter.drawText( drawRect, Qt::TextWordWrap, "Relationship between time and flight length", &boundingRect ); } else { painter.drawText( drawRect, Qt::TextWordWrap, "Relationship between time and m/z", &boundingRect ); } QwtPlotRenderer renderer; renderer.setDiscardFlag( QwtPlotRenderer::DiscardCanvasBackground, true ); renderer.setDiscardFlag( QwtPlotRenderer::DiscardCanvasFrame, true ); renderer.setDiscardFlag( QwtPlotRenderer::DiscardBackground, true ); drawRect.setTop( boundingRect.bottom() ); drawRect.setHeight( size.height() ); drawRect.setWidth( size.width() / 2 ); renderer.render( plot.get(), &painter, drawRect ); // render plot } }
void QgsComposition::print( QPrinter &printer ) { //set resolution based on composer setting printer.setFullPage( true ); printer.setColorMode( QPrinter::Color ); //set user-defined resolution printer.setResolution( printResolution() ); QPainter p( &printer ); //QgsComposition starts page numbering at 0 int fromPage = ( printer.fromPage() < 1 ) ? 0 : printer.fromPage() - 1 ; int toPage = ( printer.toPage() < 1 ) ? numPages() - 1 : printer.toPage() - 1; if ( mPrintAsRaster ) { for ( int i = fromPage; i <= toPage; ++i ) { if ( i > fromPage ) { printer.newPage(); } QImage image = printPageAsRaster( i ); if ( !image.isNull() ) { QRectF targetArea( 0, 0, image.width(), image.height() ); p.drawImage( targetArea, image, targetArea ); } } } if ( !mPrintAsRaster ) { for ( int i = fromPage; i <= toPage; ++i ) { if ( i > fromPage ) { printer.newPage(); } renderPage( &p, i ); } } }
void keyPrograms_form::printQuickPCs() { QPrinter *printer = new QPrinter(); printer->setOrientation( QPrinter::Portrait ); printer->setResolution( 600 ); // printer->setOutputFormat( QPrinter::PostScriptFormat ); QPrintDialog *dialog = new QPrintDialog( printer, this ); dialog->setWindowTitle( tr( "Print EWI Quick Patch Changes" ) ); if ( dialog->exec() != QDialog::Accepted ) return; // Create a QPainter object to draw on the printer QPainter p( printer ); QPixmap pm; pm = QPixmap::grabWidget( this ).scaledToWidth( printer->width() ); p.drawPixmap( 0, 0, pm ); //p.rotate( 90.0 ); p.end(); }
void TextEdit::filePrint() { if ( !currentEditor() ) return; #ifndef QT_NO_PRINTER QPrinter printer; printer.setFullPage(TRUE); QPaintDeviceMetrics screen( this ); printer.setResolution( screen.logicalDpiY() ); if ( printer.setup( this ) ) { QPainter p( &printer ); QPaintDeviceMetrics metrics( p.device() ); int dpix = metrics.logicalDpiX(); int dpiy = metrics.logicalDpiY(); const int margin = 72; // pt QRect body( margin * dpix / 72, margin * dpiy / 72, metrics.width() - margin * dpix / 72 * 2, metrics.height() - margin * dpiy / 72 * 2 ); QFont font( "times", 10 ); QSimpleRichText richText( currentEditor()->text(), font, currentEditor()->context(), currentEditor()->styleSheet(), currentEditor()->mimeSourceFactory(), body.height() ); richText.setWidth( &p, body.width() ); QRect view( body ); int page = 1; do { richText.draw( &p, body.left(), body.top(), view, colorGroup() ); view.moveBy( 0, body.height() ); p.translate( 0 , -body.height() ); p.setFont( font ); p.drawText( view.right() - p.fontMetrics().width( QString::number( page ) ), view.bottom() + p.fontMetrics().ascent() + 5, QString::number( page ) ); if ( view.top() >= richText.height() ) break; printer.newPage(); page++; } while (TRUE); } #endif }
void MainWindow::on_pushButton_clicked() { int current_tab = this->ui->tabWidget->currentIndex(); QPrinter printer; QTableView *myWidget; switch(current_tab) { case TABLE::StudentsTableTab: myWidget = this->ui->StudentsTableView; break; case TABLE::TeachersTableTab: myWidget = this->ui->TeachersTableView; break; default: return; } QPixmap pix = myWidget->grab(); QPainter painter; printer.setResolution(QPrinter::HighResolution); printer.setPageMargins (15,15,15,15,QPrinter::Millimeter); painter.begin(&printer); double xscale = printer.pageRect().width()/double(myWidget->width() + 50); double yscale = printer.pageRect().height()/double(myWidget->height() + 50); double scale = qMin(xscale, yscale); painter.scale(scale, scale); painter.drawPixmap(0, 0, pix); painter.end(); myWidget->render(&painter); }
void GL_widget_2::export_to_vector(QString file_name) { QPrinter printer; printer.setOutputFileName(file_name); printer.setResolution(72); printer.setPageSize(QPrinter::A0); // printer.setOrientation(QPrinter::Landscape); //ps would be not correct printer.setFullPage(true); printer.setColorMode(QPrinter::Color); QPainter painter; set_renderer_type(GL_widget_2::QT_PAINTER); set_painter(&painter); painter.begin(&printer); paint_to_painter(); painter.end(); set_painter(0); set_renderer_type(GL_widget_2::OPEN_GL); if (printer.printerState() < 2) // idle or active std::cout << "Image written to " << file_name.toStdString() << std::endl; else std::cout << "Could not write image to " << file_name.toStdString() << std::endl; }
void ExportWizard::setWallpaper() { // find a new path QString wFilePath; int fileNumber = 0; while (wFilePath.isEmpty() || QFile::exists(wFilePath)) #if defined(Q_OS_WIN) || defined(Q_OS_OS2) wFilePath = QDir::toNativeSeparators(QDir::homePath()) + QDir::separator() + "fotowall-background" + QString::number(++fileNumber) + ".bmp"; #else wFilePath = QDir::toNativeSeparators(QDir::homePath()) + QDir::separator() + "fotowall-background" + QString::number(++fileNumber) + ".jpg"; #endif // render the image QImage image; QSize sceneSize(m_canvas->width(), m_canvas->height()); QSize desktopSize = QApplication::desktop()->screenGeometry().size(); if (m_ui->wbZoom->isChecked()) image = m_canvas->renderedImage(desktopSize, Qt::KeepAspectRatioByExpanding); else if (m_ui->wbScaleKeep->isChecked()) image = m_canvas->renderedImage(desktopSize, Qt::KeepAspectRatio); else if (m_ui->wbScaleIgnore->isChecked()) image = m_canvas->renderedImage(desktopSize, Qt::IgnoreAspectRatio); else image = m_canvas->renderedImage(sceneSize); // save the right kind of image into the home dir #if defined(Q_OS_WIN) || defined(Q_OS_OS2) if (!image.save(wFilePath, "BMP")) { #else if (!image.save(wFilePath, "JPG", 100)) { #endif QMessageBox::warning(this, tr("Wallpaper Error"), tr("Can't save the image to disk.")); return; } #if defined(Q_OS_WIN) //Set new background path {QSettings appSettings("HKEY_CURRENT_USER\\Control Panel\\Desktop", QSettings::NativeFormat); appSettings.setValue("ConvertedWallpaper", wFilePath); appSettings.setValue("Wallpaper", wFilePath);} //Notification to windows refresh desktop SystemParametersInfoA(SPI_SETDESKWALLPAPER, true, (void*)qPrintable(wFilePath), SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE); #elif defined(Q_OS_LINUX) // KDE4 if (QString(qgetenv("KDE_SESSION_VERSION")).startsWith("4")) QMessageBox::warning(this, tr("Manual Wallpaper Change"), tr("KDE4 doesn't yet support changing wallpaper automatically.\nGo to the Desktop Settings and select the file:\n %1").arg(wFilePath)); // KDE3 QString kde3cmd = "dcop kdesktop KBackgroundIface setWallpaper '" + wFilePath + "' 6"; QProcess::startDetached(kde3cmd); // Gnome2 QString gnome2Cmd = "gconftool -t string -s /desktop/gnome/background/picture_filename " + wFilePath ; QProcess::startDetached(gnome2Cmd); #else #warning "Implement background change for this OS" #endif } void ExportWizard::saveImage() { if (m_ui->filePath->text().isEmpty()) { QMessageBox::warning(this, tr("No file selected !"), tr("You need to choose a file path for saving.")); return; } QString imgFilePath = m_ui->filePath->text(); // get the rendering size QSize imageSize(m_ui->saveWidth->value(), m_ui->saveHeight->value()); // render the image QImage image; bool hideTools = !m_ui->imgAsIsBox->isChecked(); if (m_ui->ibZoom->isChecked()) image = m_canvas->renderedImage(imageSize, Qt::KeepAspectRatioByExpanding, hideTools); else if (m_ui->ibScaleKeep->isChecked()) image = m_canvas->renderedImage(imageSize, Qt::KeepAspectRatio, hideTools); else image = m_canvas->renderedImage(imageSize, Qt::IgnoreAspectRatio, hideTools); // rotate image if requested if (m_ui->saveLandscape->isChecked()) { // Save in landscape mode, so rotate QMatrix matrix; matrix.rotate(90); image = image.transformed(matrix); } // save image if (image.save(imgFilePath) && QFile::exists(imgFilePath)) { int size = QFileInfo(imgFilePath).size(); QMessageBox::information(this, tr("Done"), tr("The target image is %1 bytes long").arg(size)); } else QMessageBox::warning(this, tr("Rendering Error"), tr("Error rendering to the file '%1'").arg(imgFilePath)); } void ExportWizard::startPosterazor() { static const quint32 posterPixels = 6 * 1000000; // Megapixels * 3 bytes! // We will use up the whole posterPixels for the render, respecting the aspect ratio. const qreal widthToHeightRatio = m_canvas->width() / m_canvas->height(); // Thanks to colleague Oswald for some of the math :) const int posterPixelWidth = int(sqrt(widthToHeightRatio * posterPixels)); const int posterPixelHeight = posterPixels / posterPixelWidth; static const QLatin1String settingsGroup("posterazor"); App::settings->beginGroup(settingsGroup); // TODO: Eliminate Poster size in % ImageLoaderQt loader; loader.setQImage(m_canvas->renderedImage(QSize(posterPixelWidth, posterPixelHeight))); PosteRazorCore posterazor(&loader); posterazor.readSettings(App::settings); Wizard *wizard = new Wizard; Controller controller(&posterazor, wizard); controller.setImageLoadingAvailable(false); controller.setPosterSizeModeAvailable(Types::PosterSizeModePercentual, false); QDialog dialog(this, Qt::CustomizeWindowHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint); dialog.setWindowTitle(tr("Export poster")); dialog.setLayout(new QVBoxLayout); dialog.layout()->addWidget(wizard); dialog.resize(640, 480); dialog.exec(); App::settings->sync(); posterazor.writeSettings(App::settings); App::settings->endGroup(); } bool ExportWizard::printPaper() { // update the realsizeinches, just in case.. slotPrintSizeChanged(); // get dpi, compute printed size int printDpi = m_ui->printDpi->value(); int printWidth = (int)(m_printSizeInches.width() * (float)printDpi); int printHeight = (int)(m_printSizeInches.height() * (float)printDpi); QSize printSize(printWidth, printHeight); Qt::AspectRatioMode printRatio = m_ui->printKeepRatio->isChecked() ? Qt::KeepAspectRatio : Qt::IgnoreAspectRatio; // check if print params differ from the 'Exact Size' stuff if (m_printPreferred) { if (printDpi != m_canvas->modeInfo()->printDpi()) { qWarning("ExportWizard::print: dpi changed to %d from the default %d", printDpi, (int)m_canvas->modeInfo()->printDpi()); } else { QSize exactPrintSize = m_canvas->modeInfo()->fixedPrinterPixels(); if (printSize != exactPrintSize) qWarning("ExportWizard::print: size changed to %dx%d from the default %dx%d", printWidth, printHeight, exactPrintSize.width(), exactPrintSize.height()); } } // setup printer QPrinter printer; printer.setResolution(printDpi); printer.setPaperSize(QPrinter::A4); // configure printer via the print dialog QPrintDialog printDialog(&printer); if (printDialog.exec() != QDialog::Accepted) return false; // TODO: use different ratio modes? QImage image = m_canvas->renderedImage(printSize, printRatio); if (m_ui->printLandscape->isChecked()) { // Print in landscape mode, so rotate QMatrix matrix; matrix.rotate(90); image = image.transformed(matrix); } // And then print QPainter painter; painter.drawImage(image.rect(), image); painter.end(); return true; }
void MainView::keyPressEvent(QKeyEvent *event) { if ( (event->modifiers() & Qt::ControlModifier || event->modifiers() & Qt::ShiftModifier) && event->key() == Qt::Key_Print) { event->accept(); QPrinter printer; printer.setOutputFormat(QPrinter::PdfFormat); printer.setFullPage(true); printer.setResolution(300); QSvgGenerator svggen; svggen.setResolution(90); if (event->modifiers() & Qt::ShiftModifier) { // Print scene printer.setOutputFileName("screenshot-scene.pdf"); printer.setPaperSize(scene()->sceneRect().size().toSize(), QPrinter::Point); QPainter painter(&printer); painter.setRenderHint(QPainter::Antialiasing); scene()->render( &painter ); svggen.setFileName("screenshot-scene.svg"); svggen.setSize(scene()->sceneRect().size().toSize()); QPainter svgPainter(&svggen); svgPainter.setRenderHint(QPainter::Antialiasing); scene()->render(&svgPainter); QImage image(2 * scene()->sceneRect().size().toSize(), QImage::Format_ARGB32); image.fill(Qt::transparent); QPainter pmapPainter(&image); pmapPainter.setRenderHint(QPainter::Antialiasing); //pmapPainter.scale(2,2); scene()->render(&pmapPainter); image.save("screenshot-scene.png"); } else { // Print view printer.setOutputFileName("screenshot-view.pdf"); printer.setPaperSize(viewport()->rect().size(), QPrinter::Point); QPainter painter(&printer); painter.setRenderHint(QPainter::Antialiasing); render(&painter); svggen.setFileName("screenshot-view.svg"); svggen.setSize(viewport()->rect().size()); QPainter svgPainter(&svggen); svgPainter.setRenderHint(QPainter::Antialiasing); render(&svgPainter); QImage image(2 * viewport()->rect().size(), QImage::Format_ARGB32); image.fill(Qt::transparent); QPainter pmapPainter(&image); pmapPainter.setRenderHint(QPainter::Antialiasing); render(&pmapPainter); image.save("screenshot-view.png"); } } else View::keyPressEvent(event); }
/*! Render a plot to a file Supported formats are: - pdf\n - ps\n - svg\n - all image formats supported by Qt, see QImageWriter::supportedImageFormats() \param plot Plot widget \param fileName Path of the file, where the document will be stored \param format Format for the document \param sizeMM Size for the document in millimeters. \param resolution Resolution in dots per Inch (dpi) \sa renderTo(), render(), QwtPainter::setRoundingAlignment() */ void QwtPolarRenderer::renderDocument( QwtPolarPlot *plot, const QString &fileName, const QString &format, const QSizeF &sizeMM, int resolution ) { if ( plot == NULL || sizeMM.isEmpty() || resolution <= 0 ) return; QString title = plot->title().text(); if ( title.isEmpty() ) title = "Plot Document"; const double mmToInch = 1.0 / 25.4; const QSizeF size = sizeMM * mmToInch * resolution; const QRectF documentRect( 0.0, 0.0, size.width(), size.height() ); const QString fmt = format.toLower(); if ( format == "pdf" || format == "ps" ) { QPrinter printer; printer.setFullPage( true ); printer.setPaperSize( sizeMM, QPrinter::Millimeter ); printer.setDocName( title ); printer.setOutputFileName( fileName ); printer.setOutputFormat( ( format == "pdf" ) ? QPrinter::PdfFormat : QPrinter::PostScriptFormat ); printer.setResolution( resolution ); QPainter painter( &printer ); render( plot, &painter, documentRect ); } #ifndef QWT_NO_POLAR_SVG #ifdef QT_SVG_LIB #if QT_VERSION >= 0x040500 else if ( format == "svg" ) { QSvgGenerator generator; generator.setTitle( title ); generator.setFileName( fileName ); generator.setResolution( resolution ); generator.setViewBox( documentRect ); QPainter painter( &generator ); render( plot, &painter, documentRect ); } #endif #endif #endif else { if ( QImageWriter::supportedImageFormats().indexOf( format.toLatin1() ) >= 0 ) { const QRect imageRect = documentRect.toRect(); const int dotsPerMeter = qRound( resolution * mmToInch * 1000.0 ); QImage image( imageRect.size(), QImage::Format_ARGB32 ); image.setDotsPerMeterX( dotsPerMeter ); image.setDotsPerMeterY( dotsPerMeter ); image.fill( QColor( Qt::white ).rgb() ); QPainter painter( &image ); render( plot, &painter, imageRect ); painter.end(); image.save( fileName, format.toLatin1() ); } } }
void QPrinterProto::setResolution(int dpi) { QPrinter *item = qscriptvalue_cast<QPrinter*>(thisObject()); if (item) item->setResolution(dpi); }
void Matrix::exportVector(const QString& fileName, int res, bool color, bool keepAspect, QPrinter::PageSize pageSize) { if (d_view_type != ImageView) return; if ( fileName.isEmpty() ){ QMessageBox::critical(this, tr("QtiPlot - Error"), tr("Please provide a valid file name!")); return; } QPrinter printer; printer.setCreator("QtiPlot"); printer.setFullPage(true); if (res) printer.setResolution(res); printer.setOutputFileName(fileName); if (fileName.contains(".eps")) printer.setOutputFormat(QPrinter::PostScriptFormat); if (color) printer.setColorMode(QPrinter::Color); else printer.setColorMode(QPrinter::GrayScale); int cols = numCols(); int rows = numRows(); QRect rect = QRect(0, 0, cols, rows); if (pageSize == QPrinter::Custom) printer.setPageSize(Graph::minPageSize(printer, rect)); else printer.setPageSize(pageSize); double aspect = (double)cols/(double)rows; if (aspect < 1) printer.setOrientation(QPrinter::Portrait); else printer.setOrientation(QPrinter::Landscape); if (keepAspect){// export should preserve aspect ratio double page_aspect = double(printer.width())/double(printer.height()); if (page_aspect > aspect){ int margin = (int) ((0.1/2.54)*printer.logicalDpiY()); // 1 mm margins int height = printer.height() - 2*margin; int width = int(height*aspect); int x = (printer.width()- width)/2; rect = QRect(x, margin, width, height); } else if (aspect >= page_aspect){ int margin = (int) ((0.1/2.54)*printer.logicalDpiX()); // 1 mm margins int width = printer.width() - 2*margin; int height = int(width/aspect); int y = (printer.height()- height)/2; rect = QRect(margin, y, width, height); } } else { int x_margin = (int) ((0.1/2.54)*printer.logicalDpiX()); // 1 mm margins int y_margin = (int) ((0.1/2.54)*printer.logicalDpiY()); // 1 mm margins int width = printer.width() - 2*x_margin; int height = printer.height() - 2*y_margin; rect = QRect(x_margin, y_margin, width, height); } QPainter paint(&printer); paint.drawImage(rect, d_matrix_model->renderImage()); paint.end(); }
int Printer::setResolution(lua_State * L) // ( int dpi ) { QPrinter* lhs = ValueBinding<MyQPrinter>::check( L, 1 ); lhs->setResolution( Util::toInt( L, 2 )); return 0; }
//--------------------------------------------------------------- void SkewTWindow::actionsCommonSlot () { setCursor (Qt::WaitCursor); QObject *send = sender (); if (send == acExit) { this->hide (); this->destroy (); if (skewt) { delete skewt; skewt = nullptr; } } else if (send == cbTempMax) { int v = cbTempMax->itemData (cbTempMax->currentIndex()).toInt(); Util::setSetting ("skewt_tempCMax", v); skewt->setTempPressLimits (v, skewt->getHpaMin()); } else if (send == cbHpaMin) { int v = cbHpaMin->itemData (cbHpaMin->currentIndex()).toInt(); Util::setSetting ("skewt_hpaMin", v); skewt->setTempPressLimits (skewt->getTempCMax(), v-10); } else if (send == cbSizeW) { double sz = cbSizeW->itemData (cbSizeW->currentIndex()).toDouble(); Util::setSetting ("skewt_sizeW", sz); skewt->setSkewTSize (sz, skewt->height()); } else if (send == cbSizeH) { double sz = cbSizeH->itemData (cbSizeH->currentIndex()).toDouble(); Util::setSetting ("skewt_sizeH", sz); skewt->setSkewTSize (skewt->width(), sz); } else if (send == cbConvBase) { QString cbase = cbConvBase->itemData (cbConvBase->currentIndex()).toString(); Util::setSetting ("skewt_convectiveBase", cbase); skewt->setConvectiveBase (cbase); } else if (send == chkShowConv) { Util::setSetting ("skewt_showConvectiveCurves", chkShowConv->isChecked()); skewt->resetGraphic (); cbConvBase->setEnabled (chkShowConv->isChecked()); } else if (send == acPrint) { QPrinter printer; printer.setOutputFormat (QPrinter::PdfFormat); printer.setResolution (150); QPrintDialog *dialog = new QPrintDialog(&printer, this); dialog->setWindowTitle (tr("Print Document")); if (dialog->exec() == QDialog::Accepted) { QPainter painter; painter.begin(&printer); double xscale = printer.pageRect().width()/double(skewt->width()); double yscale = printer.pageRect().height()/double(skewt->height()); double scale = qMin(xscale, yscale); painter.translate(printer.paperRect().x() + printer.pageRect().width()/2, printer.paperRect().y() + printer.pageRect().height()/2); painter.scale(scale, scale); painter.translate(-skewt->width()/2, -skewt->height()/2); skewt->setPrinterRendering (true); skewt->render (&painter); skewt->setPrinterRendering (false); } } else if (send == acSaveImage) { QString filename = Util::getSetting("skewt_imageSaveFilename", "").toString(); filename = Util::getSaveFileName (this, tr("Save JPEG image"), filename, tr("Images (*.jpg *.jpeg)") ); if (filename != "") { if ( ! filename.endsWith(".jpg", Qt::CaseInsensitive) && ! filename.endsWith(".jpeg", Qt::CaseInsensitive) ) filename += ".jpg"; Util::setSetting("skewt_imageSaveFilename", filename); QImage image (skewt->size(), QImage::Format_RGB32); skewt->setPrinterRendering (true); skewt->render (&image); skewt->setPrinterRendering (false); image.save (filename, "JPEG", 96); } } else if (send == acExportData) { QString path = Util::getSetting("slkFilePath", "").toString(); if (path == "") path = "./"; else path += "/"; QString fileName; fileName = Util::getSaveFileName (this, tr("Save SYLK file"), path, "*.slk"); if (fileName != "") { if (! fileName.endsWith(".slk", Qt::CaseInsensitive)) fileName += ".slk"; SylkFile slk (fileName, "XyGrib"); if (slk.isOk()) { Util::setSetting("slkFilePath", slk.getFileInfo().absolutePath() ); saveFileSYLK (slk); slk.close (); } else { QMessageBox::critical (this, tr("Error"), tr("Can't write file.")); } } } unsetCursor (); }
void MainWindow::on_StartButton_clicked() { double A=ui->ASpin->value(), B=ui->BSpin->value(), N=ui->NSpin->value(), TMax=ui->TMaxSpin->value(), Eps=ui->EpsSpin->value(); RungeKutta rk = RungeKutta(A, B, N, TMax, Eps); ui->Qwt_Widget->detachItems(QwtPlotItem::Rtti_PlotCurve, true); rk.run(); //QCustomPlot* customPlot = ui->MainPlot; //customPlot->addGraph(); //customPlot->graph(0)->setData(rk.y1, rk.y2); // for(int i=0; i<N; i++) // { // qDebug()<<"y1["<<i<<"]= "<<rk.y1[i]<<endl; // } // for(int i=0; i<N; i++) // { // qDebug()<<"y2["<<i<<"]= "<<rk.y2[i]<<endl; // } // customPlot->xAxis->setLabel("y1"); // customPlot->yAxis->setLabel("y2"); // if(rk.y1[0]<rk.y1[N]) // customPlot->xAxis->setRange(rk.y1[0], rk.y1[N-1]); // else // customPlot->xAxis->setRange(rk.y1[N-1], rk.y1[0]); // if(rk.y2[0]<rk.y2[N]) // customPlot->yAxis->setRange(rk.y2[0], rk.y2[N-1]); // else // customPlot->yAxis->setRange(rk.y2[N-1], rk.y2[0]); // customPlot->replot(); min1=min(rk.y1,rk.p1); min2=min(rk.y2,rk.p2); max1=max(rk.y1,rk.p1); max2=max(rk.y2,rk.p2); ui->Qwt_Widget->setAxisScale(QwtPlot::xBottom, min1 , max1); ui->Qwt_Widget->setAxisScale(QwtPlot::yLeft, min2 , max2); ui->Qwt_Widget->replot();//чтобы сразу приблизить наблюдателя к графику // рисуем кривую addCurve(rk); QString abcs; abcs.setNum(c); c++; const QString filename = "C:/Users/Kirill/Desktop/Prac/report/"+abcs+".pdf"; QPrinter printer; printer.setOutputFormat(QPrinter::PdfFormat); printer.setOrientation(QPrinter::Landscape); printer.setResolution(80); printer.setPaperSize(QPrinter::A4); printer.setFullPage(true); printer.setOutputFileName(filename); QImage image= QPixmap::grabWidget(ui->Qwt_Widget).toImage(); // image.setDotsPerMeterX(500); image.scaled(1000,1000, Qt::KeepAspectRatio); // image.setDotsPerMeterY(500); QPainter painter; painter.begin(&printer); painter.drawImage(0,0,image); painter.end(); //сделаем красивые графики в гнуплоте(выведем массивы в файл) QFile file("C:/Users/Kirill/Desktop/Prac/report/"+abcs+".txt"); file.open(QIODevice::WriteOnly | QIODevice::Text); QTextStream out(&file); out.setRealNumberPrecision(10); for (int i=0; i<N ; i++) out << rk.t[i] <<' ' << rk.y1[i]<<' '<<rk.y2[i]<<"\n"; }
void TSController::printReport() { // qDebug()<<"TSController::printReport"; QPrinter printer; QPrintDialog *dialog = new QPrintDialog(&printer, this); dialog->setWindowTitle(tr("Предварительный просмотр")); int endIndex=curveBuffer->lenght; float listh=printer.widthMM()*printer.resolution()/25.4-60; float listw=printer.heightMM()*printer.resolution()/25.4-60; printer.setPageMargins(5,5,5,5,QPrinter::Millimeter); printer.setOrientation(QPrinter::Landscape); printer.setResolution(QPrinter::HighResolution); printer.setPaperSize(QPrinter::A4); Ui::Form pf; pf.setupUi(&wpf); pf.mainBox->setMaximumSize((int)listw,(int)listh); pf.mainBox->setMinimumSize((int)listw,(int)listh); pf.resultsTable->setMinimumWidth(40+(int)listw/3); pf.resultsTable->setRowCount(13); pf.resultsTable->setColumnCount(2); pf.resultsTable->verticalHeader()->setVisible(false); pf.resultsTable->setHorizontalHeaderLabels(QString(tr("Параметр; Значение")).split(";")); pf.resultsTable->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); int i=0,j=0; for(i=0;i<ui->resultsTable->rowCount();i++){ for(j=0;j<2;j++){ pf.resultsTable->setItem(i,j,getQTableWidgetItem(ui->resultsTable->item(i,j)->text())); } } int myH=0,myW=0; wpf.resize(pf.mainBox->size()); wpf.show(); myH = pf.gVolume->height(); myW = pf.gVolume->width(); QPixmap pmTempIn(myW,myH); QPixmap pmTempOut(myW,myH); QPixmap pmVolume(myW,myH); QPainter prTempIn; QPainter prTempOut; QPainter prVolume; prTempIn.begin(&pmTempIn); prTempOut.begin(&pmTempOut); prVolume.begin(&pmVolume); int h = pf.gVolume->height()/2; int step = h/10; if(h%10>=5) { h+=step/2; } prVolume.fillRect(0,0,myW,myH,Qt::white); prTempIn.fillRect(0,0,myW,myH,Qt::white); prTempOut.fillRect(0,0,myW,myH,Qt::white); prVolume.setPen(QColor(225,225,225)); prTempIn.setPen(QColor(225,225,225)); prTempOut.setPen(QColor(225,225,225)); for(i=step;i<h;i+=step) { prVolume.drawLine(0,h+i,myW,h+i); prTempIn.drawLine(0,h+i,myW,h+i); prTempOut.drawLine(0,h+i,myW,h+i); prVolume.drawLine(0,h-i,myW,h-i); prTempIn.drawLine(0,h-i,myW,h-i); prTempOut.drawLine(0,h-i,myW,h-i); } for(i=10;i<myW;i+=10) { prVolume.drawLine(i,0,i,h<<1); prTempIn.drawLine(i,0,i,h<<1); prTempOut.drawLine(i,0,i,h<<1); } prVolume.setPen(QColor(0,0,0)); prTempIn.setPen(QColor(0,0,0)); prTempOut.setPen(curveBuffer->toutColor); prVolume.setPen(QColor(255,0,0)); int* tinInt = curveBuffer->getTempInInterval(); int* toutInt = curveBuffer->getTempOutInterval(); int* volInt = curveBuffer->getVolumeInterval(); float tempInK = 1; float tempOutK = 1; float tempInZ = h; float tempOutZ = h; tempInAdaptive = (float)myH/(tinInt[1]-tinInt[0]); tempOutAdaptive = (float)myH/(toutInt[1]-toutInt[0]); volumeAdaptive = (float)myH/(volInt[1]-volInt[0]); tempInZ = h + ceil((float)(tinInt[1]+tinInt[0])*tempInAdaptive*tempInK/2); tempOutZ = h + ceil((float)(toutInt[1]+toutInt[0])*tempOutAdaptive*tempOutK/2); float volumeK =1; i=0; int k=ceil((float)curveBuffer->lenght/pf.gTempIn->width()); for(j=0;j<myW-35;j+=1) { if(i>=k*endIndex)break; prVolume.drawLine( j,h-volumeK*volumeAdaptive*volume[i],j+1,h-volumeK*volumeAdaptive*volume[i+k] ); prTempIn.drawLine(j,tempInZ-tempInK*tempInAdaptive*tempIn[i] ,j+1,tempInZ-tempInK*tempInAdaptive*tempIn[i+k]); prTempOut.drawLine(j,tempOutZ-tempOutK*tempOutAdaptive*tempOut[i] ,j+1,tempOutZ-tempOutK*tempOutAdaptive*tempOut[i+k]); i+=k; } pf.gVolume->setPixmap(pmVolume); pf.gTempIn->setPixmap(pmTempIn); pf.gTempOut->setPixmap(pmTempOut); pf.PatientName->setText(patientsModel->record(0).value("sname").toString()+" "+patientsModel->record(0).value("fname").toString()); wpf.hide(); if (dialog->exec() == QDialog::Accepted){ QPainter painter; painter.begin(&printer); int i=0; pf.mainBox->render(&painter); } }
void MainView::keyPressEvent(QKeyEvent *event) { if ( (event->modifiers() & Qt::ControlModifier || event->modifiers() & Qt::ShiftModifier) && event->key() == Qt::Key_Print) { event->accept(); QPrinter printer; printer.setOutputFormat(QPrinter::PdfFormat); printer.setFullPage(true); printer.setResolution(300); QSvgGenerator svggen; svggen.setResolution(90); if (event->modifiers() & Qt::ShiftModifier) { // Print scene printer.setOutputFileName("screenshot-scene.pdf"); printer.setPaperSize(scene()->sceneRect().size().toSize(), QPrinter::Point); QPainter painter(&printer); painter.setRenderHint(QPainter::Antialiasing); scene()->render( &painter ); svggen.setFileName("screenshot-scene.svg"); svggen.setSize(scene()->sceneRect().size().toSize()); QPainter svgPainter(&svggen); svgPainter.setRenderHint(QPainter::Antialiasing); scene()->render(&svgPainter); QImage image(2 * scene()->sceneRect().size().toSize(), QImage::Format_ARGB32); image.fill(Qt::transparent); QPainter pmapPainter(&image); pmapPainter.setRenderHint(QPainter::Antialiasing); //pmapPainter.scale(2,2); scene()->render(&pmapPainter); image.save("screenshot-scene.png"); } else { // Print view printer.setOutputFileName("screenshot-view.pdf"); printer.setPaperSize(viewport()->rect().size(), QPrinter::Point); QPainter painter(&printer); painter.setRenderHint(QPainter::Antialiasing); render(&painter); svggen.setFileName("screenshot-view.svg"); svggen.setSize(viewport()->rect().size()); QPainter svgPainter(&svggen); svgPainter.setRenderHint(QPainter::Antialiasing); render(&svgPainter); QImage image(2 * viewport()->rect().size(), QImage::Format_ARGB32); image.fill(Qt::transparent); QPainter pmapPainter(&image); pmapPainter.setRenderHint(QPainter::Antialiasing); render(&pmapPainter); image.save("screenshot-view.png"); } } else if (event->modifiers() == Qt::NoModifier && event->key() == Qt::Key_F11) { event->accept(); QWidget* window = this; while (window->parentWidget()) window = window->parentWidget(); if (window->isFullScreen()) window->showNormal(); else window->showFullScreen(); } else if (event->modifiers() == Qt::NoModifier && event->key() == Qt::Key_F10) { event->accept(); if (miniMap->width() == MINIMAP_DEFAULT_WIDTH && miniMap->height() == MINIMAP_DEFAULT_HEIGHT) setMiniMapSize(width(), height()); else setMiniMapSize(MINIMAP_DEFAULT_WIDTH, MINIMAP_DEFAULT_HEIGHT); } else if (event->modifiers() == Qt::NoModifier && event->key() == Qt::Key_F9) { event->accept(); if (miniMap->isVisible()) miniMap->hide(); else miniMap->show(); } else if (event->modifiers() == Qt::NoModifier && event->key() == Qt::Key_F7) { event->accept(); showTimers_ = ~showTimers_; updateInfoLabels(); } else View::keyPressEvent(event); }
bool ChequePrinter::print() { // 0. Amount to readable string QString amount; QStringList vals = Utils::doubleToHumanReadableString(d->_amount); if (vals.count() == 0) { LOG_ERROR_FOR("ChecquePrinter", "Wrong amount to string values"); } else { amount = vals.at(0) + " " + QLocale().currencySymbol(QLocale::CurrencyDisplayName) + "s"; if (vals.count() == 2) amount += QString(" %1 %2").arg(tkTr(Trans::Constants::AND)).arg(vals.at(1)); } // Method 1. use pdkcompleter // Internal::PdfTkWrapper *pdftk = Internal::PdfTkWrapper::instance(); // if (!pdftk->initialize()) // return false; // pdftk->beginFdfEncoding(); // pdftk->addFdfValue("date", QLocale().toString(d->_date, QLocale::ShortFormat)); // pdftk->addFdfValue("lieu", d->_place); // pdftk->addFdfValue("ordre", d->_order); // pdftk->addFdfValue("montant1", lines.at(0)); // if (lines.count() >= 2) // pdftk->addFdfValue("montant2", lines.at(1)); // // Amount to translated number // QSystemLocale::CurrencyToStringArgument arg; // arg.value = d->_amount; // QVariant var; // var.setValue<QSystemLocale::CurrencyToStringArgument>(arg); // pdftk->addFdfValue("num", QString::number(d->_amount, 'f', 2)); //QSystemLocale().query(QSystemLocale::CurrencyToString, var).toString()); // QString filename = "/Users/eric/Desktop/cheque.pdf"; // pdftk->endFdfEncoding(filename); // pdftk->fillPdfWithFdf(filename, pdftk->getFdfContent(), "/Users/eric/Desktop/test_cheque.pdf", "ISO-8859-1"); // return true; // Method 2. use QPainter/QPrinter // try to use the default printer QPrintDialog dlg; if (dlg.exec()==QDialog::Rejected) return false; QPrinter *printer = dlg.printer(); // printer->setPaperSource(QPrinter::PaperSource); printer->setFullPage(true); printer->setPaperSize(QPrinter::A4); printer->setResolution(150); printer->setOrientation(QPrinter::Landscape); d->_axisHelper.setPageSize(printer->paperRect(), printer->paperSize(QPrinter::Millimeter)); QPainter painter; if (!painter.begin(printer)) { // failed to open file qWarning("failed to open file, is it writable?"); return false; } painter.save(); QFont font; font.setPointSize(10); painter.setFont(font); painter.translate(d->_axisHelper.pointToPixels(120, 61)); // 25,17 pour certains // 45,13 pour d'autres QRectF amountLines(d->_axisHelper.pointToPixels(45,13), d->_axisHelper.sizeToPixels(90, 10)); // QRect amountLine2(d->_axisHelper.pointToPixels(10,23), d->size(110, 5)); QRectF orderLine(d->_axisHelper.pointToPixels(10,28), d->_axisHelper.sizeToPixels(110, 5)); QRectF numberLine(d->_axisHelper.pointToPixels(133,28), d->_axisHelper.sizeToPixels(41, 10)); QRectF placeLine(d->_axisHelper.pointToPixels(133,38), d->_axisHelper.sizeToPixels(40, 4)); QRectF dateLine(d->_axisHelper.pointToPixels(133,42), d->_axisHelper.sizeToPixels(40, 4)); if (DrawChequeRects) { painter.drawRect(amountLines); painter.drawRect(orderLine); painter.drawRect(numberLine); painter.drawRect(placeLine); painter.drawRect(dateLine); } if (amount.count() > 50) amount = Utils::lineWrapString(amount, 50); amount = QString("****%1****").arg(amount.toUpper()); QFontMetrics metrics(font); while (metrics.width(amount) > amountLines.width() || font.pointSize() == 6) { font.setPointSizeF(font.pointSizeF() - .1); metrics = QFontMetrics(font); } painter.setFont(font); painter.drawText(amountLines, Qt::AlignLeft, amount); font.setPointSize(10); painter.setFont(font); // QStringList lines = amount.split("\n", QString::SkipEmptyParts); // painter.drawText(amountLine1, Qt::AlignLeft | Qt::AlignVCenter, lines.at(0)); // if (lines.count() >= 2) // painter.drawText(amountLine2, Qt::AlignLeft | Qt::AlignVCenter, lines.at(1)); painter.drawText(orderLine, Qt::AlignLeft | Qt::AlignVCenter, d->_order.toUpper()); font.setBold(true); painter.setFont(font); painter.drawText(numberLine, Qt::AlignCenter | Qt::AlignVCenter, QString("****%1****").arg(QLocale().toString(d->_amount, 'f', 2)) //.arg(QLocale().toCurrencyString(d->_amount, "*")) );//QString::number(d->_amount, 'f', 2)); //QSystemLocale().query(QSystemLocale::CurrencyToString, var).toString()); font.setPointSize(10); font.setBold(false); metrics = QFontMetrics(font); d->_place = d->_place.toUpper(); while (metrics.width(d->_place) > placeLine.width() && font.pointSize() > 6) { font.setPointSizeF(font.pointSizeF() - .1); metrics = QFontMetrics(font); } painter.setFont(font); painter.drawText(placeLine, Qt::AlignLeft | Qt::AlignVCenter, d->_place); font.setPointSize(10); painter.setFont(font); painter.drawText(dateLine, Qt::AlignLeft | Qt::AlignVCenter, d->_date.toString(Qt::SystemLocaleShortDate)); //QLocale().toString(d->_date, QLocale::ShortFormat)); painter.restore(); painter.end(); return true; }
void HeliCanvas::save(QString streamID, QString headline, QString date, QString filename, int xres, int yres, int dpi) { std::cerr << "Printing..." << std::flush; QPainter *painter; QFileInfo fi(filename); QPrinter *printer = NULL; QImage *pixmap = NULL; if ( fi.suffix().toLower() == "ps" ) { printer = new QPrinter(QPrinter::HighResolution); printer->setOutputFileName(filename); printer->setResolution(dpi); printer->setPageSize(QPrinter::A4); painter = new QPainter(printer); } else { pixmap = new QImage(xres,yres,QImage::Format_RGB32); painter = new QPainter(pixmap); painter->fillRect(painter->window(), _palette.color(QPalette::Base)); } painter->setFont(SCScheme.fonts.base); int fontHeight = painter->fontMetrics().height(); int headerHeight = fontHeight*120/100; if ( !headline.isEmpty() ) headerHeight += fontHeight*120/100; painter->translate(0, headerHeight); int offset = draw( *painter, QSize(painter->viewport().width(), painter->viewport().height()-headerHeight) ); painter->translate(0, -headerHeight); painter->drawText(offset, 0, painter->viewport().width()-offset, fontHeight, Qt::AlignLeft | Qt::AlignTop, streamID); painter->drawText(offset, 0, painter->viewport().width()-offset, fontHeight, Qt::AlignRight | Qt::AlignTop, date); if ( !headline.isEmpty() ) painter->drawText(offset, fontHeight*120/100, painter->viewport().width()-offset, fontHeight, Qt::AlignLeft | Qt::AlignTop, headline); painter->drawLine(0, headerHeight, painter->viewport().width(), headerHeight); if ( pixmap ) pixmap->save(filename); painter->end(); // Clean up if ( printer ) delete printer; if ( pixmap ) delete pixmap; if ( painter ) delete painter; std::cerr << "finished" << std::endl; }
void SceneImageExporter::GraphicsSceneToPrinter( QGraphicsScene *scene, QPrinter& printer, QString fileName, QString documentName __attribute__((unused)), bool bSizeToOneSheet) { if (!fileName.isEmpty() && fileName != "" && fileName.endsWith(".pdf",Qt::CaseInsensitive)) { printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(fileName); } // When printing, use full page mode, IE ignore hardware margins. It's up // to users to set them as they desire. printer.setFullPage(true); printer.setPaperSize(QSizeF(PrintingPreferences::prefs().selectedMeasure().width(), PrintingPreferences::prefs().selectedMeasure().height()), QPrinter::Millimeter); printer.setPageMargins(PrintingPreferences::prefs().leftMargin(), PrintingPreferences::prefs().topMargin(), PrintingPreferences::prefs().rightMargin(), PrintingPreferences::prefs().bottomMargin(), QPrinter::Millimeter); if (!bSizeToOneSheet) { //here, I print using selected sheets and divisions. QPainter painter(&printer); qreal left,top,right,bottom; printer.getPageMargins(&left,&top,&right,&bottom,QPrinter::DevicePixel); // get the FULL PAGE RECTANGLE and adjust margins. QRectF pageRect = printer.paperRect(); pageRect.adjust(left,top,-right, -bottom); //get height/width page rect ratio double pageRatio = pageRect.width()/pageRect.height(); //get scene rectangle and calculating pages. int stepY = PrintingPreferences::prefs().yDivisions(); QRectF sceneRect = scene->sceneRect(); double scene_dy = sceneRect.height()/( (double)stepY); double scene_dx = scene_dy * pageRatio; double o_scene_dx = scene_dx * 1.1; double o_scene_dy = scene_dy * 1.1; double o_rect_dx = pageRect.width() / 1.1; double o_rect_dy = pageRect.height() / 1.1; double odx = ( pageRect.width() -o_rect_dx)/2.0; double ody = (pageRect.height() - o_rect_dy)/ 2.0; QRectF pageRectInner = QRectF (pageRect.left() + odx, pageRect.top() + ody, o_rect_dx, o_rect_dy); int stepX = 1+ (int)(sceneRect.width() / scene_dx); //ok, calculated my boxes. NOW, let's print everything out. QColor transparent(0,0,0,0); QColor transBorder (0,0,0,128); QPen pen (transBorder); pen.setStyle(Qt::DotLine); QBrush brush(transparent); bool bNewPage = false; for (int y = 0; y < stepY; y++) { for (int x = 0; x < stepX; x++) { if (bNewPage) printer.newPage(); else bNewPage = true; //I've already got my target rectangle QRectF sourceRect = QRectF ( sceneRect.left()+((double)x * scene_dx + (o_scene_dx - scene_dx)/2.0 ), sceneRect.top()+((double)y * scene_dy + (o_scene_dy - scene_dy)/2.0), o_scene_dx,o_scene_dy); scene->render(&painter,pageRect, sourceRect); QBrush oldBrush = painter.brush(); QPen oldPen = painter.pen(); //qDebug() << "pageRect " << pageRect; //qDebug() << "pageRectInner " << pageRectInner; painter.setPen(pen); painter.setBrush(brush); painter.drawRect(pageRect); painter.drawRect(pageRectInner); painter.setPen(oldPen); painter.setBrush(oldBrush); } } painter.end(); } else { QRectF sceneRect = scene->sceneRect(); //qDebug() << "scene Rect:" << sceneRect; printer.setResolution(96); printer.setPaperSize(QSizeF ( scene->sceneRect().width()+(76*2), scene->sceneRect().height()+(76*2)), QPrinter::DevicePixel); printer.setFullPage(true); printer.setPageMargins( 76.0,76.0,76.0,76.0, QPrinter::DevicePixel); QPainter painter(&printer); qreal left,top,right,bottom; printer.getPageMargins(&left,&top,&right,&bottom,QPrinter::DevicePixel); QRectF pageRect = printer.paperRect(); //qDebug() << "pageRect: " << pageRect; pageRect = pageRect.adjusted(left,top,-right,-bottom); //qDebug() << "pageRect: " << pageRect; //qDebug() << "sceneRect: " << sceneRect; scene->render(&painter,pageRect, sceneRect, Qt::IgnoreAspectRatio); //qDebug() << left << "," << right << "," << top << "," << bottom; //qDebug() << printer.paperRect().left() << "," // << printer.paperRect().width() << "," // << printer.paperRect().top() << "," // << printer.paperRect().height(); pageRect = printer.pageRect(); //qDebug() << pageRect.left() << "," // << pageRect.width() << "," // << pageRect.top() << "," // << pageRect.height(); QColor transparent(0,0,0,0); QColor transBorder (0,0,0,128); QPen pen (transBorder); pen.setStyle(Qt::DotLine); QBrush brush(transparent); painter.setPen(pen); painter.setBrush(brush); painter.drawRect(pageRect); painter.end(); } }
void Global::generatePDFs(QString dirname) { size_t pageCount = 0; for (size_t s = 0; s < getNumStudents(); s++) { Student& student = db()->getStudent(s); // Use the student name to form the file name for the repot QString clean = student.getStudentName(); // Convert all non alpha/num chars into an underscore for (QString::iterator i = clean.begin(); i != clean.end(); i++) { if (!i->isLetterOrNumber()) *i = '_'; } if (clean.length() == 0) { GINFODIALOG(QString("Cannot render PDF because student %1 does not have a name assigned").arg(s+1)); return; } QString pdfname (dirname + "/report-" + clean + ".pdf"); GDEBUG ("Generating PDF [%s] for student [%s]", qPrintable(pdfname), qPrintable(student.getStudentId())); QPrinter printer (QPrinter::HighResolution); printer.setOutputFormat (QPrinter::PdfFormat); printer.setOutputFileName (pdfname); printer.setPageSize(QPrinter::Letter); printer.setResolution(150); // DPI for the printing printer.setColorMode(QPrinter::GrayScale); QPainter painter; if (!painter.begin(&printer)) // Check for errors here GFATAL("Failed to do QPainter begin()"); // Can use this code to change the text color, but causes larger PDF files // since it must use a color output format instead. //QPen penColor(QColor("#000090")); // Change text to dark blue //painter.setPen(penColor); for (size_t p = 0; p < getNumPagesPerStudent(); p++) { pageCount++; // Add spaces at the end so the widget can resize into the reserved space without a re-layout Global::getStatusLabel()->setText(QString("Generating PDF for student %1 of %2, page %3 of %4 (%5 percent) "). arg(s+1).arg(getNumStudents()).arg(p+1).arg(getNumPagesPerStudent()).arg(rint(0.5+100.0*pageCount/(1.0*getNumPages())))); // Flush out Qt events so that the UI update occurs inside this handler Global::getQApplication()->processEvents(); GDEBUG ("Printing page %zu of %zu for report [%s]", p+1, getNumPagesPerStudent(), qPrintable(pdfname)); QPixmap pix = getPages()->getQPixmap(p+s*getNumPagesPerStudent()); // Scale the pixmap to fit the printer pix = pix.scaled(printer.pageRect().width(), printer.pageRect().height(), Qt::KeepAspectRatio); // Draw the pixmap to the printer painter.drawPixmap (0, 0, pix); // Print out the student details at the top of the page QString title = QString("Name: %1 ID: %2 Page: %3 of %4 Final Grade: %5 of %6").arg(student.getStudentName()).arg(student.getStudentId()).arg(p+1).arg(getNumPagesPerStudent()).arg(student.getTotal()).arg(db()->getTotalMaximum()); painter.drawText(0, 0, title); // Build up a results string to print onto the page QString grades ("Results:"); size_t pageTotal = 0; size_t pageMax = 0; for (size_t q = 0; q < getNumQuestions(); q++) { // See if the question is on this page GASSERT(Global::db()->getQuestionPage(q) != 0, "Cannot have page 0 assigned for question %zu", q); if (Global::db()->getQuestionPage(q) < 0) { GINFODIALOG(QString("Cannot render PDF because question %1 does not have a page assigned").arg(q+1)); return; } if (Global::db()->getQuestionPage(q) == ((int)p+1)) { if (student.getGrade(q) < 0) { GINFODIALOG(QString("Cannot render PDF for student [%1] because question %2 has no grade assigned").arg(student.getStudentName()).arg(q+1)); return; } pageTotal += student.getGrade(q); pageMax += Global::db()->getQuestionMaximum(q); grades += QString(" Q%1 = %2/%3").arg(q+1).arg(student.getGrade(q)).arg(Global::db()->getQuestionMaximum(q)); if (student.getFeedback(q) != "") grades += QString(" [%1]").arg(student.getFeedback(q)); } } grades += QString(" Totals = %1/%2").arg(pageTotal).arg(pageMax); if (pageMax == 0) grades = QString("No Results For This Page"); // Wrap the text to fit a bounding box that is the width of the page, align to the bottom of the page painter.drawText(0, 30, printer.pageRect().width(), printer.pageRect().height()-30, Qt::TextWordWrap | Qt::AlignBottom, grades); // Insert a new page except on the last one if (p < getNumPagesPerStudent()-1) if (!printer.newPage()) // Check for errors here GFATAL("Failed to do newPage() call"); } painter.end(); } Global::getStatusLabel()->setText(""); }