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 MultiLayer::exportVector(const QString &fileName, int res, bool color, bool keepAspect, QPrinter::PageSize pageSize, QPrinter::Orientation orientation) { Q_UNUSED(res); if (fileName.isEmpty()) { QMessageBox::critical(this, tr("Error"), tr("Please provide a valid file name!")); return; } QPrinter printer; printer.setDocName(this->name()); printer.setCreator("AlphaPlot"); printer.setFullPage(true); printer.setOutputFileName(fileName); if (fileName.contains(".eps")) printer.setOutputFormat(QPrinter::PostScriptFormat); if (color) printer.setColorMode(QPrinter::Color); else printer.setColorMode(QPrinter::GrayScale); if (pageSize == QPrinter::Custom) printer.setPaperSize(canvas->size(), QPrinter::Point); else { printer.setOrientation(orientation); printer.setPaperSize(pageSize); } exportPainter(printer, keepAspect); }
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 Printer::print() { // we can only print if "PRINT" mode is selected if (printMode != Printer::PRINT) { return; } QPrinter *printerPtr; printerPtr = static_cast<QPrinter*>(paintDevice); TemplateLayout t(printOptions, templateOptions); connect(&t, SIGNAL(progressUpdated(int)), this, SLOT(templateProgessUpdated(int))); dpi = printerPtr->resolution(); //rendering resolution = selected paper size in inchs * printer dpi pageSize.setHeight(qCeil(printerPtr->pageRect(QPrinter::Inch).height() * dpi)); pageSize.setWidth(qCeil(printerPtr->pageRect(QPrinter::Inch).width() * dpi)); webView->page()->setViewportSize(pageSize); webView->page()->mainFrame()->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAlwaysOff); // export border width with at least 1 pixel // templateOptions->borderwidth = std::max(1, pageSize.width() / 1000); if (printOptions->type == print_options::DIVELIST) { webView->setHtml(t.generate()); } else if (printOptions->type == print_options::STATISTICS ) { webView->setHtml(t.generateStatistics()); } if (printOptions->color_selected && printerPtr->colorMode()) { printerPtr->setColorMode(QPrinter::Color); } else { printerPtr->setColorMode(QPrinter::GrayScale); } // apply user settings int divesPerPage; // get number of dives per page from data-numberofdives attribute in the body of the selected template bool ok; divesPerPage = webView->page()->mainFrame()->findFirstElement("body").attribute("data-numberofdives").toInt(&ok); if (!ok) { divesPerPage = 1; // print each dive in a single page if the attribute is missing or malformed //TODO: show warning } int Pages; if (divesPerPage == 0) { flowRender(); } else { Pages = qCeil(getTotalWork(printOptions) / (float)divesPerPage); render(Pages); } }
void KexiReportView::slotExportAsPdf() { QScopedPointer<KoReportRendererBase> renderer(m_factory.createInstance("print")); if (renderer) { KoReportRendererContext cxt; cxt.destinationUrl = getExportUrl(QLatin1String("application/pdf"), xi18n("Export Report as PDF"), "kfiledialog:///LastVisitedPDFExportPath/", "pdf"); if (!cxt.destinationUrl.isValid()) { return; } QPrinter printer; QPainter painter; printer.setOutputFileName(cxt.destinationUrl.path()); printer.setOutputFormat(QPrinter::PdfFormat); printer.setColorMode(QPrinter::Color); painter.begin(&printer); cxt.printer = &printer; cxt.painter = &painter; if (!renderer->render(cxt, m_reportDocument)) { KMessageBox::error(this, xi18n("Exporting the report as PDF to %1 failed.", cxt.destinationUrl.toDisplayString()), xi18n("Export Failed")); } else { openExportedDocument(cxt.destinationUrl); } } }
int Printer::setColorMode(lua_State * L) // ( ColorMode newColorMode ) { QPrinter* lhs = ValueBinding<MyQPrinter>::check( L, 1 ); QPrinter::ColorMode f=(QPrinter::ColorMode)Util::toInt( L, 2 ); lhs->setColorMode( f ); return 0; }
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 MyTextBrowser::slotPRINTER() { QPrinter printer; printer.setColorMode(QPrinter::Color); QPrintDialog dialog(&printer); if (dialog.exec() == QDialog::Accepted) { PRINT(&printer); } }
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 MainWindow::saveAsPdf(const QString& fileName) const { if (fileName != "") { QPrinter pdfPrinter; pdfPrinter.setOutputFormat(QPrinter::PdfFormat); pdfPrinter.setOutputFileName(fileName); pdfPrinter.setColorMode(QPrinter::Color); Printer::applySettings(&pdfPrinter, printer); QPainter painter(&pdfPrinter); view->paint(painter, pdfPrinter); } }
void CompareDialog::on_printFileButton_clicked() { QPrinter printer; QString filename = QFileDialog::getSaveFileName(this, tr("Select PDF output file"), QString(), "Pdf File(*.pdf)"); printer.setPageMargins(10.0, 10.0, 10.0, 10.0, printer.Millimeter); printer.setOutputFormat(QPrinter::PdfFormat); printer.setOrientation(QPrinter::Landscape); printer.setColorMode(QPrinter::Color); if (!filename.isEmpty()) { if (QFileInfo(filename).suffix().isEmpty()) filename.append(".pdf"); printer.setOutputFileName(filename); ui->textEdit->print(&printer); } }
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 Matrix::print(const QString& fileName) { QPrinter printer; printer.setColorMode (QPrinter::GrayScale); if (!fileName.isEmpty()){ printer.setCreator("QtiPlot"); printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(fileName); } else { QPrintDialog printDialog(&printer, applicationWindow()); if (printDialog.exec() != QDialog::Accepted) return; } printer.setFullPage( true ); print(&printer); }
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 MultiLayer::print() { QPrinter printer; printer.setColorMode(QPrinter::Color); printer.setFullPage(true); QRect canvasRect = canvas->rect(); double aspect = double(canvasRect.width()) / double(canvasRect.height()); if (aspect < 1) printer.setOrientation(QPrinter::Portrait); else printer.setOrientation(QPrinter::Landscape); QPrintDialog printDialog(&printer); if (printDialog.exec() == QDialog::Accepted) { QPainter paint(&printer); printAllLayers(&paint); paint.end(); } }
void PrintDialog::printToFile() { if (printfilename.isEmpty()) return; if (! (printfilename.endsWith(".odt", Qt::CaseInsensitive) || printfilename.endsWith(".pdf", Qt::CaseInsensitive) || printfilename.endsWith(".htm", Qt::CaseInsensitive) || printfilename.endsWith(".html", Qt::CaseInsensitive)) ) printfilename += ".pdf"; // default if (printfilename.endsWith(".pdf", Qt::CaseInsensitive)) { QPrinter printer; printer.setPageMargins(10.0,10.0,10.0,10.0,printer.Millimeter); printer.setOutputFormat(QPrinter::PdfFormat); printer.setColorMode(QPrinter::Color); printer.setOutputFileName(printfilename); ui->textEdit->print(&printer); } else { QTextDocumentWriter writer(printfilename); writer.write(ui->textEdit->document()); } }
void PrintDialog::on_printFileButton_clicked() { QString fn = QFileDialog::getSaveFileName(this,tr("Select PDF output file"),QString(),tr("ODF files (*.odt);;PDF Files(*.pdf);;HTML-Files (*.htm *.html);;All Files (*)")); if (fn.isEmpty()) return; if (! (fn.endsWith(".odt", Qt::CaseInsensitive) || fn.endsWith(".pdf", Qt::CaseInsensitive) || fn.endsWith(".htm", Qt::CaseInsensitive) || fn.endsWith(".html", Qt::CaseInsensitive)) ) fn += ".pdf"; // default if (fn.endsWith(".pdf", Qt::CaseInsensitive)) { QPrinter printer; printer.setPageMargins(10.0,10.0,10.0,10.0,printer.Millimeter); printer.setOutputFormat(QPrinter::PdfFormat); printer.setColorMode(QPrinter::Color); printer.setOutputFileName(fn); ui->textEdit->print(&printer); } else { QTextDocumentWriter writer(fn); writer.write(ui->textEdit->document()); } }
void MainWindow::slotPrint() { #ifndef NO_PRINTER if(opt.arg_debug) printf("slotPrint\n"); QWidget *w = centralWidget(); if(w == NULL) { QMessageBox::information (this, "pvbrowser", tr("no printable contents")); return; } QPixmap pm; QPrinter printer; printer.setOrientation(QPrinter::Landscape); printer.setColorMode(QPrinter::Color); snapshot(pm); QPrintDialog printDialog(&printer, this); if(printDialog.exec() == QDialog::Accepted) { // print ... QPainter painter; painter.begin(&printer); if(strlen(l_print_header.toUtf8()) > 0) { QString date_time; date_time = l_print_header; date_time += QDateTime::currentDateTime().toString(Qt::TextDate); date_time += " "; date_time += pvbtab[currentTab].url; painter.drawText(LEFT_PRINT_MARGIN,UPPER_PRINT_MARGIN-30,1280,100,Qt::TextExpandTabs, date_time); } QPixmap pmprint = pm.scaledToWidth(painter.viewport().width()-LEFT_PRINT_MARGIN*2, Qt::SmoothTransformation); painter.drawPixmap(LEFT_PRINT_MARGIN,UPPER_PRINT_MARGIN,pmprint); painter.end(); } #endif }
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 Clamp::print() { #if 1 QPrinter printer; #else QPrinter printer(QPrinter::HighResolution); #if QT_VERSION < 0x040000 printer.setOutputToFile(true); printer.setOutputFileName("/tmp/FI.ps"); printer.setColorMode(QPrinter::Color); #else printer.setOutputFileName("/tmp/FI.pdf"); #endif #endif QString docName = splot->title().text(); if (!docName.isEmpty()) { docName.replace(QRegExp(QString::fromLatin1("\n")), tr(" -- ")); printer.setDocName(docName); } printer.setCreator("RTXI"); printer.setOrientation(QPrinter::Landscape); #if QT_VERSION >= 0x040000 QPrintDialog dialog(&printer); if ( dialog.exec() ) { #else if (printer.setup()) { #endif /* RTXIPrintFilter filter; if (printer.colorMode() == QPrinter::GrayScale) { int options = QwtPlotPrintFilter::PrintAll; filter.setOptions(options); filter.color(QColor(29, 100, 141), QwtPlotPrintFilter::CanvasBackground); filter.color(Qt::white, QwtPlotPrintFilter::CurveSymbol); } */ // splot->print(printer, filter); QwtPlotRenderer *renderer = new QwtPlotRenderer; renderer->renderTo(splot, printer); } } void Clamp::exportSVG() { QString fileName = "FI.svg"; std::cout<<"flag 0"<<std::endl; #if QT_VERSION < 0x040000 std::cout<<"flag 1"<<std::endl; #ifndef QT_NO_FILEDIALOG std::cout<<"flag 2"<<std::endl; fileName = QFileDialog::getSaveFileName("FI.svg", "SVG Documents (*.svg)", this); #endif std::cout<<"flag 3"<<std::endl; if (!fileName.isEmpty()) { // enable workaround for Qt3 misalignments QwtPainter::setSVGMode(true); QPicture picture; QPainter p(&picture); // splot->print(&p, QRect(0, 0, 800, 600)); QwtPlotRenderer *renderer = new QwtPlotRenderer; renderer->renderTo(splot, p, QRect(0, 0, 800, 600)); p.end(); picture.save(fileName, "svg"); } #elif QT_VERSION >= 0x040300 std::cout<<"flag 4"<<std::endl; #ifdef QT_SVG_LIB std::cout<<"flag 5"<<std::endl; #ifndef QT_NO_FILEDIALOG std::cout<<"flag 6"<<std::endl; fileName = QFileDialog::getSaveFileName(this, "Export File Name", QString(), "SVG Documents (*.svg)"); #endif std::cout<<"flag 7"<<std::endl; if ( !fileName.isEmpty() ) { QSvgGenerator generator; generator.setFileName(fileName); generator.setSize(QSize(800, 600)); // splot->print(generator); } #endif #endif }
void QPrinterProto::setColorMode(QPrinter::ColorMode newColorMode) { QPrinter *item = qscriptvalue_cast<QPrinter*>(thisObject()); if (item) item->setColorMode(newColorMode); }
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(); }
void Matrix::print(const QString& fileName) { QPrinter printer; printer.setColorMode (QPrinter::GrayScale); if (!fileName.isEmpty()){ printer.setCreator("QtiPlot"); printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(fileName); } else { QPrintDialog printDialog(&printer, applicationWindow()); if (printDialog.exec() != QDialog::Accepted) return; } printer.setFullPage( true ); QPainter p; if ( !p.begin(&printer ) ) return; // paint on printer int dpiy = printer.logicalDpiY(); const int margin = (int) ( (1/2.54)*dpiy ); // 1 cm margins if (d_view_type == ImageView){ p.drawImage (printer.pageRect(), d_matrix_model->renderImage()); return; } QHeaderView *vHeader = d_table_view->verticalHeader(); int rows = numRows(); int cols = numCols(); int height = margin; int i, vertHeaderWidth = vHeader->width(); int right = margin + vertHeaderWidth; // print header p.setFont(QFont()); QString header_label = d_matrix_model->headerData(0, Qt::Horizontal).toString(); QRect br = p.boundingRect(br, Qt::AlignCenter, header_label); p.drawLine(right, height, right, height+br.height()); QRect tr(br); for(i=0; i<cols; i++){ int w = d_table_view->columnWidth(i); tr.setTopLeft(QPoint(right,height)); tr.setWidth(w); tr.setHeight(br.height()); header_label = d_matrix_model->headerData(i, Qt::Horizontal).toString(); p.drawText(tr, Qt::AlignCenter, header_label,-1); right += w; p.drawLine(right, height, right, height+tr.height()); if (right >= printer.width()-2*margin ) break; } p.drawLine(margin + vertHeaderWidth, height, right-1, height);//first horizontal line height += tr.height(); p.drawLine(margin, height, right-1, height); // print table values for(i=0;i<rows;i++){ right = margin; QString cell_text = d_matrix_model->headerData(i, Qt::Horizontal).toString()+"\t"; tr = p.boundingRect(tr, Qt::AlignCenter, cell_text); p.drawLine(right, height, right, height+tr.height()); br.setTopLeft(QPoint(right,height)); br.setWidth(vertHeaderWidth); br.setHeight(tr.height()); p.drawText(br,Qt::AlignCenter,cell_text,-1); right += vertHeaderWidth; p.drawLine(right, height, right, height+tr.height()); for(int j=0; j<cols; j++){ int w = d_table_view->columnWidth (j); cell_text = text(i,j)+"\t"; tr = p.boundingRect(tr,Qt::AlignCenter,cell_text); br.setTopLeft(QPoint(right,height)); br.setWidth(w); br.setHeight(tr.height()); p.drawText(br, Qt::AlignCenter, cell_text, -1); right += w; p.drawLine(right, height, right, height+tr.height()); if (right >= printer.width()-2*margin ) break; } height += br.height(); p.drawLine(margin, height, right-1, height); if (height >= printer.height()-margin ){ printer.newPage(); height = margin; p.drawLine(margin, height, right, height); } } }
bool Screenshot::SaveScreenShotToPdf(QPixmap screenShot, QString fileName, QPrinter::Orientation orientation, QPrinter::PageSize pageSize, QPrinter::ColorMode colorMode) { QByteArray encodedString; QTextCodec* codec = QTextCodec::codecForName("Windows-1251");; QString appendText, titleMessage; Qt::WindowFlags flag = 0; flag |= Qt::Tool;// Удаление значка с taskbar и кнопок максимум, минимум размера окна flag |= Qt::WindowStaysOnTopHint;// Всегда поверх других flag |= Qt::FramelessWindowHint; flag |= Qt::WindowTitleHint; QDateTime date_time = QDateTime::currentDateTime(); QMessageBox msgBox; msgBox.setWindowTitle(date_time.toString() + " " + QApplication::applicationName() + ":" + QApplication::applicationVersion()); msgBox.setWindowFlags(flag); // Step 1. Убедится, что screenshot не пустой if(screenShot.isNull()){ encodedString = "Сообщение"; titleMessage = codec->toUnicode(encodedString); encodedString = "В буфере обмена ничего нет"; msgBox.setText(titleMessage); // Заголовок сообщения msgBox.setIcon(QMessageBox::Information); // Тип иконки сообщения msgBox.setInformativeText(appendText); // Основное сообщение Message Box msgBox.setDefaultButton(QMessageBox::Save); // На какой кнопке фокусироваться по умолчанию msgBox.exec(); return 0; }//if // Step 2. Убедится, что fileName не пустой if (fileName.isEmpty()){ encodedString = "Сообщение"; titleMessage = codec->toUnicode(encodedString); encodedString = "Имя файла не указано"; appendText = codec->toUnicode(encodedString); msgBox.setText(titleMessage); // Заголовок сообщения msgBox.setIcon(QMessageBox::Information); // Тип иконки сообщения msgBox.setInformativeText(appendText); // Основное сообщение Message Box msgBox.setDefaultButton(QMessageBox::Save); // На какой кнопке фокусироваться по умолчанию msgBox.exec(); return 0; }//if // Расширение файла fileName += ".pdf"; // Step 3. Проверка существования файла. Если файл существует, то решить, нужно ли его перезаписывать if (QFile::exists(fileName)){ encodedString = "Процедура сохранения"; titleMessage = codec->toUnicode(encodedString); encodedString = " \nуже существует. Заменить?"; appendText = codec->toUnicode(encodedString); msgBox.setText(titleMessage); // Заголовок сообщения msgBox.setIcon(QMessageBox::Information); // Тип иконки сообщения msgBox.setInformativeText(fileName + appendText); // Основное сообщение Message Box msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Cancel); // Добавление реагирования на софт клавиши msgBox.setDefaultButton(QMessageBox::Save); // На какой кнопке фокусироваться по умолчанию int ret = msgBox.exec(); // Запускаем QMessageBox. После выполнения, в ret будет лежать значение кнопки, на которую нажали - это необходимо для дальнейшей обработки событий if(ret == QMessageBox::Cancel) return 0; }//if // Step 4. Объявление экземпляра класса QPrinter и определение его настроек QPrinter printer; printer.setOutputFileName(fileName); printer.setFullPage(true); printer.setOutputFormat(QPrinter::PdfFormat); printer.setPaperSize(pageSize); printer.setOrientation(orientation); printer.setColorMode(colorMode); printer.newPage(); // Step 5. Проверка на возможные ошибки QPainter painter; if (! painter.begin(&printer)){ encodedString = "Ошибка открытия файла"; titleMessage = codec->toUnicode(encodedString); encodedString = "Убедитесь, что запись в файл разрешена"; appendText = codec->toUnicode(encodedString); msgBox.setText(titleMessage); // Заголовок сообщения msgBox.setIcon(QMessageBox::Warning); // Тип иконки сообщения msgBox.setInformativeText(appendText); // Основное сообщение Message Box msgBox.setDefaultButton(QMessageBox::Save); // На какой кнопке фокусироваться по умолчанию msgBox.show(); return 0; }//if /* if (! printer.newPage()){ encodedString = "Ошибка при добавлении новой страницы"; titleMessage = codec->toUnicode(encodedString); encodedString = "Убедитесь, что на диске есть место"; appendText = codec->toUnicode(encodedString); msgBox.setText(titleMessage); // Заголовок сообщения msgBox.setIcon(QMessageBox::Warning); // Тип иконки сообщения msgBox.setInformativeText(appendText); // Основное сообщение Message Box msgBox.setDefaultButton(QMessageBox::Save); // На какой кнопке фокусироваться по умолчанию msgBox.show(); return 0; }//if */ // Step 6. Сохранение painter.drawPixmap(0, 0, printer.width(), printer.height(), screenShot); painter.end(); /* QFile file("c://test.txt"); file.open(QIODevice::Append | QIODevice::Text); QTextStream out(&file); out << temp; out << "\n"; file.close(); */ return 1; }
/*! Render a plot to a file Supported formats are: - pdf\n Portable Document Format PDF - ps\n Postcript - svg\n Scalable Vector Graphics SVG - all image formats supported by Qt\n see QImageWriter::supportedImageFormats() Scalable vector graphic formats like PDF or SVG are superior to raster graphics formats. \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 QwtPlotRenderer::renderDocument( QwtPlot *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 ( fmt == "pdf" ) { #ifndef QT_NO_PRINTER QPrinter printer; printer.setColorMode( QPrinter::Color ); printer.setFullPage( true ); printer.setPaperSize( sizeMM, QPrinter::Millimeter ); printer.setDocName( title ); printer.setOutputFileName( fileName ); printer.setOutputFormat( QPrinter::PdfFormat ); printer.setResolution( resolution ); QPainter painter( &printer ); render( plot, &painter, documentRect ); #endif } else if ( fmt == "ps" ) { #if QT_VERSION < 0x050000 #ifndef QT_NO_PRINTER QPrinter printer; printer.setColorMode( QPrinter::Color ); printer.setFullPage( true ); printer.setPaperSize( sizeMM, QPrinter::Millimeter ); printer.setDocName( title ); printer.setOutputFileName( fileName ); printer.setOutputFormat( QPrinter::PostScriptFormat ); printer.setResolution( resolution ); QPainter painter( &printer ); render( plot, &painter, documentRect ); #endif #endif } else if ( fmt == "svg" ) { #ifndef QWT_NO_SVG #ifdef QT_SVG_LIB #if QT_VERSION >= 0x040500 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() ); } } }
/// Writes all the relevant data into the tdf file. void ExportEPS::doExport() { using namespace std; // code adapted from Umbrello bool exportSuccessful; QRect textrect; //out->close(); // print the image to a normal postscript file, // do not clip so that everything ends up in the file // regardless of "paper size" // because we want to work with postscript // user-coordinates, set to the resolution // of the printer (which should be 72dpi here) QPrinter *printer; printer = new QPrinter(QPrinter::ScreenResolution); printer->setOutputToFile(true); printer->setOutputFormat(QPrinter::PostScriptFormat); printer->setOutputFileName(fileName); printer->setColorMode(QPrinter::Color); printer->setFontEmbeddingEnabled(true); // do not call printer.setup(); because we want no user // interaction here QPainter *painter = new QPainter(printer); // make sure the widget sizes will be according to the // actually used printer font, important for getDiagramRect() // and the actual painting //view->forceUpdateWidgetFontMetrics(painter); if (!scrollview) { delete painter; delete printer; exportSuccessful = FALSE; } Draw* draw = new Draw(scrollview, options); QRect rect = draw->getBoundingBox(machine, painter); rect.setWidth(rect.width()+10); rect.setHeight(rect.height()+10); painter->translate(-rect.x(),-rect.y()); //view->getDiagram(rect,*painter); int resolution = printer->resolution(); if (scrollview) scrollview->getDrawArea()->getSelection()->deselectAll(machine); draw->drawStates(machine, painter, 0, 0, 1.0); draw->drawTransitions(machine, painter, 0, 0, 1.0); if (machine->getDrawITrans()) draw->drawInitialTransition(machine, machine->getInitialTransition(), painter, 0, 0, 1.0, textrect, FALSE); // delete painter and printer before we try to open and fix the file delete painter; delete printer; delete draw; // modify bounding box from screen to eps resolution. rect.setWidth( int(ceil(rect.width() * 72.0/resolution)) ); rect.setHeight( int(ceil(rect.height() * 72.0/resolution)) ); exportSuccessful = fixEPS(fileName,rect); // next painting will most probably be to a different device (i.e. the screen) //view->forceUpdateWidgetFontMetrics(0); if (scrollview) scrollview->getDrawArea()->reset(); //return exportSuccessful; }
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(""); }
void Matrix::print() { QPrinter printer; printer.setColorMode (QPrinter::GrayScale); if (printer.setup()) { printer.setFullPage( TRUE ); QPainter p; if ( !p.begin(&printer ) ) return; // paint on printer QPaintDeviceMetrics metrics( p.device() ); int dpiy = metrics.logicalDpiY(); const int margin = (int) ( (1/2.54)*dpiy ); // 1 cm margins QHeader *hHeader = d_table->horizontalHeader(); QHeader *vHeader = d_table->verticalHeader(); int rows=d_table->numRows(); int cols=d_table->numCols(); int height=margin; int i,vertHeaderWidth=vHeader->width(); int right = margin + vertHeaderWidth; // print header p.setFont(QFont()); QRect br=p.boundingRect(br,Qt::AlignCenter, hHeader->label(0),-1,0); p.drawLine(right,height,right,height+br.height()); QRect tr(br); for (i=0;i<cols;i++) { int w=d_table->columnWidth (i); tr.setTopLeft(QPoint(right,height)); tr.setWidth(w); tr.setHeight(br.height()); p.drawText(tr,Qt::AlignCenter,hHeader->label(i),-1); right+=w; p.drawLine(right,height,right,height+tr.height()); if (right >= metrics.width()-2*margin ) break; } p.drawLine(margin + vertHeaderWidth, height, right-1, height);//first horizontal line height+=tr.height(); p.drawLine(margin,height,right-1,height); // print d_table values for (i=0;i<rows;i++) { right=margin; QString text=vHeader->label(i)+"\t"; tr=p.boundingRect(tr,Qt::AlignCenter,text,-1,0); p.drawLine(right,height,right,height+tr.height()); br.setTopLeft(QPoint(right,height)); br.setWidth(vertHeaderWidth); br.setHeight(tr.height()); p.drawText(br,Qt::AlignCenter,text,-1); right+=vertHeaderWidth; p.drawLine(right,height,right,height+tr.height()); for (int j=0;j<cols;j++) { int w=d_table->columnWidth (j); text=d_table->text(i,j)+"\t"; tr=p.boundingRect(tr,Qt::AlignCenter,text,-1,0); br.setTopLeft(QPoint(right,height)); br.setWidth(w); br.setHeight(tr.height()); p.drawText(br,Qt::AlignCenter,text,-1); right+=w; p.drawLine(right,height,right,height+tr.height()); if (right >= metrics.width()-2*margin ) break; } height+=br.height(); p.drawLine(margin,height,right-1,height); if (height >= metrics.height()-margin ) { printer.newPage(); height=margin; p.drawLine(margin,height,right,height); } } } }