void Matrix::exportVector(const QString& fileName, int res, bool color)
{
    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("Analysis");
	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 SchedulePrintDialog::setupPrinter( QPrinter & printer )
{
	printer.setPageSize( QPrinter::PageSize(mPageSizeCombo->currentIndex()) );
	printer.setOrientation( mOrientationCombo->currentText() == "Landscape" ? QPrinter::Landscape : QPrinter::Portrait );
}
void MainWindow::saveParameterStatistic( const QString &s_FilenameIn, const QVector<PlotSettings> &v_PS, const int i_Format )
{
    QPrinter        printer;
    QTextDocument   textDocu;
    QFont           textFont            = QFont( gf_HeaderTextFont.family(), 10, 0, false );

    QFileInfo fi( s_FilenameIn );

    QString         s_FilenameParamStat = fi.absolutePath() + "/" + fi.baseName() + "_param_stat.";
    QString         s_FileDescr         = "";

// **********************************************************************************************

    switch ( i_Format )
    {
    case _FORMATPDF_:
        s_FilenameParamStat.append( "pdf" );
        s_FileDescr = tr( "Portable document format (*.pdf)" );
        break;
    default:
        s_FilenameParamStat.append( "txt" );
        s_FileDescr = tr( "Text (*.txt)" );
        break;
    }

    #if defined(Q_OS_LINUX)
        s_FilenameParamStat = QFileDialog::getSaveFileName(this, tr( "Save parameter statistic to file" ), s_FilenameParamStat, s_FileDescr, 0, QFileDialog::DontUseNativeDialog );
    #endif

    #if defined(Q_OS_WIN)
        s_FilenameParamStat = QFileDialog::getSaveFileName(this, tr( "Save parameter statistic to file" ), s_FilenameParamStat, s_FileDescr, 0, QFileDialog::DontUseNativeDialog );
    #endif

    #if defined(Q_OS_MAC)
        s_FilenameParamStat = QFileDialog::getSaveFileName(this, tr( "Save parameter statistic to file" ), s_FilenameParamStat, s_FileDescr, 0, QFileDialog::DontUseNativeDialog );
    #endif

    switch ( i_Format )
    {
    case _FORMATPDF_:
        printer.setOrientation( QPrinter::Landscape );
        printer.setOutputFileName( s_FilenameParamStat );

        textDocu.setHtml( createParameterStatisticOutputText( fi.fileName(), v_PS ) );
        textDocu.setDefaultFont( textFont );
        textDocu.print( &printer );
        break;

    default:
        QFile fout( s_FilenameParamStat );

        if ( fout.open( QIODevice::WriteOnly | QIODevice::Text ) == true )
        {
            QTextStream tout( &fout );

            tout << "Parameter settings of:\t" << fi.fileName() << endl << endl;

            tout << "Parameter name" << "\t" << "Minimum" << "\t" << "Maximum" << "\t" << "Median" << "\t" << "Mean" << "\t" << "Std dev" << "\t" << "Type" << endl;

            for ( int i=0; i<v_PS.count(); i++ )
            {
                tout << v_PS.at( i ).Parameter() << "\t";

                if ( v_PS.at( i ).Type() == isDateTime )
                {
                    tout << QString( "%1" ).arg( QDate::fromJulianDay( (int) v_PS.at( i ).YMinimum() ).toString( Qt::ISODate ) ) << "\t";
                    tout << QString( "%1" ).arg( QDate::fromJulianDay( (int) v_PS.at( i ).YMaximum() ).toString( Qt::ISODate ) ) << "\t";
                    tout << "\t" << "\t" << "\t";
                    tout << "Date/Time" << endl;
                }
                else
                {
                    if ( v_PS.at( i ).Type() != isText )
                    {
                        if ( v_PS.at( i ).YMinimum() < 10E99 )
                            tout << QString( "%1" ).arg( v_PS.at( i ).YMinimum() ) << "\t";
                        else
                            tout << "\t";

                        if ( v_PS.at( i ).YMaximum() > -10E99 )
                            tout << QString( "%1" ).arg( v_PS.at( i ).YMaximum() ) << "\t";
                        else
                            tout << "\t";

                        if ( v_PS.at( i ).isGeocode() == false )
                        {
                            if ( v_PS.at( i ).Median() != -999. )
                                tout  << QString( "%1" ).arg( v_PS.at( i ).Median() ) << "\t";
                            else
                                tout << "\t";

                            if ( v_PS.at( i ).Mean() != -999. )
                                tout  << QString( "%1" ).arg( v_PS.at( i ).Mean() ) << "\t";
                            else
                                tout << "\t";

                            if ( v_PS.at( i ).StandardDeviation() != -999. )
                                tout << QString( "%1" ).arg( v_PS.at( i ).StandardDeviation() ) << "\t";
                            else
                                tout << "\t";
                        }
                    }

                    if ( v_PS.at( i ).Type() == isNumeric )
                        tout << "Numeric";

                    if ( v_PS.at( i ).Type() == isText )
                        tout << "\t" << "\t" << "\t" << "\t" << "\t" << "Text";

                    tout << endl;
                }
            }

            fout.close();
        }
        break;
    }
}
示例#4
0
void QPrinterProto::setOrientation(QPrinter::Orientation orientation)
{
  QPrinter *item = qscriptvalue_cast<QPrinter*>(thisObject());
  if (item)
    item->setOrientation(orientation);
}
示例#5
0
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();
}
示例#6
0
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";

}
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;
}
示例#8
0
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 Data_analysis_gui::save_as_image( const QString& filename, 
                                       const QString& format,
                                       bool show_stats, bool show_grid ) {
  // get a file name and the name of the filter to use to save the image.
  // 3 filters are available: PNG, BMP, and Postscript. Postscript is not
  // available on Windows (Qt limitation).


  // Create a blank image of the correct dimensions
  int extra_width = 15;
  int min_height = 0;
  if( show_stats ) {
    extra_width = 200;
    min_height = 250;
  }
  QSize total_size( plot_->size().width() + extra_width, 
                    std::max( min_height, plot_->size().height()+10 ) );
  QPixmap pix( total_size );
  pix.fill();
  QPainter painter( &pix );
  

  // draw the content of the plot

  QwtPlotPrintFilter filter;
  if( show_grid )
    filter.setOptions( QwtPlotPrintFilter::PrintTitle | QwtPlotPrintFilter::PrintGrid );
  else
    filter.setOptions( QwtPlotPrintFilter::PrintTitle );

  QRect rect = plot_->rect();
  rect.setY( rect.y() + 10 );
  plot_->print( &painter, rect, filter );


  // Add the summary statistics to the image if requested

  if( show_stats ) {
    QFont font = plot_->axisFont( QwtPlot::xBottom );
    painter.setFont( font );
    int text_y_start = std::max( 40, total_size.height()/2 - 100 );
    painter.translate( plot_->size().width()+15 , text_y_start );
    paint_stats( painter );
  }


  // Finally, save the pixmap in the required format

  if( format == "Postscript" || format == "PS" ) {
    /*
#if defined(WIN32) || defined(_WIN32)
    if (show_stats)
		build_stats();
    SimplePs ps(filename,plot_, _stats,show_stats);
	if (!ps.isopen()){
		QMessageBox::warning(this,"Unable to save file",
		"Failed to save ps file",QMessageBox::Ok,
		Qt::NoButton);
		return;
	}
	savePostScript(ps);

#else
    */
    QPrinter printer;
    
    printer.setOutputFormat(QPrinter::PostScriptFormat);
    printer.setOutputFileName( filename );
    printer.setPageSize( QPrinter::A6 );
    printer.setFullPage( true );
    printer.setOrientation( QPrinter::Landscape );
    plot_->print(printer, filter);

    QPainter P(&printer);
    //P.begin(&printer);
    //paint_stats(P);
    P.drawPixmap(QPoint(0,0),pix);

    //#endif
  }
  else {
    QByteArray tmp = format.toLatin1();
    pix.save( filename, tmp.constData() );
  }

}
void PrintAPI::PrintA4(QString title, QString type, QList<QString> columnNames, QList<int> columnWidths,
                       QStringList content)
{
    //计算行数列数
    int columnCount = columnNames.count();
    int rowCount = content.count();

    //清空原有数据,确保每次都是新的数据
    html.clear();

    //表格开始
    html.append("<table border='0.5' cellspacing='0' cellpadding='3'>");

    //标题占一行,居中显示
    html.append(QString("<tr><td colspan='%1'>").arg(columnCount));
    html.append("<p align='center' style='vertical-align:middle;font-weight:bold;font-size:15px;'>");
    html.append(title);
    html.append("</p></td></tr>");

    //循环写入字段名,字段名占一行,居中显示
    html.append("<tr>");
    for (int i = 0; i < columnCount; i++) {
        html.append(QString("<td width='%1' bgcolor='lightgray'>").arg(columnWidths.at(i)));
        html.append("<p align='center' style='vertical-align:middle;'>");
        html.append(columnNames.at(i));
        html.append("</p></td>");
    }
    html.append("</tr>");

    //循环一行行构建数据
    for (int i = 0; i < rowCount; i++) {
        QStringList value = content.at(i).split(";");
        html.append("<tr>");
        for (int j = 0; j < columnCount; j++) {
            html.append(QString("<td width='%1'>").arg(columnWidths.at(j)));
            html.append(value.at(j));
            html.append("</td>");
        }
        html.append("</tr>");
    }

    html.append("</table>");

    //调用打印机打印
    QPrinter printer;
    //设置输出格式
    printer.setOutputFormat(QPrinter::NativeFormat);
    //设置纸张规格
    printer.setPageSize(QPrinter::A4);
    //设置横向纵向及页边距
    if (type == "横向") {
        printer.setOrientation(QPrinter::Landscape);
        printer.setPageMargins(10, 10, 10, 12, QPrinter::Millimeter);
    } else {
        printer.setOrientation(QPrinter::Portrait);
        printer.setPageMargins(10, 10, 10, 16, QPrinter::Millimeter);
    }

    QPrintPreviewDialog preview(&printer);
    preview.setWindowTitle("打印预览");
    connect(&preview, SIGNAL(paintRequested(QPrinter *)), this, SLOT(printView(QPrinter *)));
    preview.showMaximized();
    preview.exec();
}
示例#11
0
//-----------------------------------------------------------
void CenaObjetos::definirGrade(unsigned tam)
{
 if(tam >= 20 || grade.style()==Qt::NoBrush)
 {
  QImage img_grade;
  float larg, alt, x, y;
  QSizeF tam_aux;
  QPrinter printer;
  QPainter painter;
  QPen pen;

  //Caso o tamanho do papel não seja personalizado
  if(tam_papel!=QPrinter::Custom)
  {
   //Configura um dispositivo QPrinter para obter os tamanhos de página
   printer.setPageSize(tam_papel);
   printer.setOrientation(orientacao_pag);
   printer.setPageMargins(margens_pag.left(), margens_pag.top(),
                          margens_pag.right(), margens_pag.bottom(), QPrinter::Millimeter);
   tam_aux=printer.pageRect(QPrinter::DevicePixel).size();
  }
  //Caso o tipo de papel seja personalizado, usa as margens como tamanho do papel
  else
   tam_aux=margens_pag.size();


  larg=fabs(roundf(tam_aux.width()/static_cast<float>(tam)) * tam);
  alt=fabs(roundf(tam_aux.height()/static_cast<float>(tam)) * tam);

  //Cria uma instância de QImage para ser a textura do brush
  tam_grade=tam;
  img_grade=QImage(larg, alt, QImage::Format_ARGB32);

  //Aloca um QPaointer para executar os desenhos sobre a imagem
  painter.begin(&img_grade);

  //Limpa a imagem
  painter.fillRect(QRect(0,0,larg,alt), QColor(255,255,255));

  if(exibir_grade)
  {
   //Cria a grade
   pen.setColor(QColor(225, 225, 225));
   painter.setPen(pen);

   for(x=0; x < larg; x+=tam)
    for(y=0; y < alt; y+=tam)
     painter.drawRect(QRectF(QPointF(x,y),QPointF(x + tam,y + tam)));
  }

  //Cria as linhas que definem o limite do papel
  if(exibir_lim_pagina)
  {
   pen.setColor(QColor(75,115,195));
   pen.setStyle(Qt::DashLine);
   pen.setWidthF(1.85f);
   painter.setPen(pen);
   painter.drawLine(larg-1, 0,larg-1,alt-1);
   painter.drawLine(0, alt-1,larg-1,alt-1);
  }

  painter.end();
  grade.setTextureImage(img_grade);
 }
}
示例#12
0
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;
}
示例#13
0
qint8 FaxToMailModule::Process()
{
        qDebug()<<"FaxToMailProcess Start\n";
        this->FIFolder.setPath(this->SysS->faxInfoFolderPath);//FaxInfoFolder
        this->FDFolder.setPath(this->SysS->faxDataFolderPath);//FaxDateFolder
        this->FileFilter.clear();
        this->FileFilter.append("*.FI");
        this->FIFolder.setNameFilters(this->FileFilter);
        qint32 FileCount=this->FIFolder.count();
        qDebug()<<"FileCount="<<FileCount<<"\n";
        QStringList FIFileList = this->FIFolder.entryList(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot);

        while (!FIFileList.isEmpty())
            {
                QString FIFilePath,qcode;
                //qDebug()<<FIFileList.first();
                FIFilePath.clear();
                FIFilePath.append(this->FIFolder.absolutePath()+"/"+FIFileList.first());
                qDebug()<<FIFilePath;

                QFile FIfile(FIFilePath);
                if (!FIfile.open(QIODevice::ReadWrite|QIODevice::Text)) return -1;
                QByteArray tmp;
                tmp=FIfile.readLine();
                qDebug()<<"Identify code="<<QString(tmp);
                //qcode=QString(tmp);
                tmp=FIfile.readLine();
                qDebug()<<"Identify Mailaddr="<<QString(tmp);
                this->MailTo=QString(tmp);
                tmp=FIfile.readLine();
                while(!QString(tmp).isEmpty())
                {
                    //qDebug()<<QString(tmp);
                    FDFilePath.clear();
                    FDFilePath.append(tmp);
                    FDFilePath.remove("\n");
                    //qDebug()<<FDFilePath;
                    //Re=FaxIdentify(qcode,MailTo);
                    if (Re==true)
                    {
                       qDebug()<<"begin to print\n";

                       QPrinter printer;
                       printer.setOutputFormat(QPrinter::PdfFormat);
                       printer.setOrientation(QPrinter::Landscape);
                       printer.setPageSize(QPrinter::B0);
                       printer.setOutputFileName("/tmp/nonwritable.pdf");
                       QPainter painter;
                       QImage Image;
                       Image.load(FDFilePath);
                       qDebug()<<Image.size();
                       if (! painter.begin(&printer))
                       { // failed to open file
                            qWarning("failed to open file, is it writable?");
                            return -1;
                       }
                       painter.drawImage(0,0,Image);
                       /*
                       QFont font("Times",50);
                       QString text = tr("Hello World");
                       painter.setPen(Qt::blue);
                       painter.setFont(font);
                       painter.drawText(QRect(0,0, 1000, 100), text);
                        */
                       painter.end();

                        QFile PDFFile("/tmp/nonwritable.pdf");
                        if(PDFFile.open(QIODevice::ReadOnly))
                        {


                            QByteArray ls;
                            ls=PDFFile.readAll();
                            PDFFile.close();
                            //qDebug()<<"File Size="<<ls.size();
                            this->MailAttachment=ls.toBase64();
                            //qDebug()<<ls.toBase64();
                            if (this->CheckMailServerInfo()<0)
                            {
                                qDebug()<<"Error:MailServerInfo="<<this->CheckMailServerInfo();
                            }
                            else
                            {
                                QList<QString> bcc;
                                bcc<<"*****@*****.**";

                                Smtp *mail=new Smtp(this->MailServer,this->MailFrom,this->MailTo,bcc,"You have a fax !!!!!","You got a fax!!!",true,this->MailAttachment);
                                mail->current_user_name=this->MailUsername;
                                mail->current_password=this->MailPassword;
                                //qDebug()<<"ready,begin to sent mail";
                                mail->send();
                                //mail->~Smtp();

                            }


                        }
                        else
                        {
                            qFatal("Can Not find the PDF file!!!");
                        }

                    }
                    else
                    {

                    }

                    tmp=FIfile.readLine();
                }
                FIfile.close();
                FIfile.remove(FIfile.fileName());
                FIFileList.removeFirst();
            }
    //}
    FaxToMailTimer.start(3*1000);
    qDebug()<<"FaxToMailProcess End\n";
    return true;
}
示例#14
0
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
}