//! Print the checked in and missing items.
void wndInventoryCheck::printReport( void )
{
    QPrinter printer;
    printer.setPaperSize( QPrinter::Letter );
    printer.setPageMargins( 1, 1, 1, 1, QPrinter::Inch );

    QPrintDialog *dialog = new QPrintDialog( &printer, this );
    if ( dialog->exec() != QDialog::Accepted )
    {
        return;
    }

    // PDF printing:
    //printer.setOutputFormat(QPrinter::PdfFormat);
    //printer.setOutputFileName("test.pdf");

    // Build the painter data which is printed
    QPainter painter;

    if ( !painter.begin( &printer ) ) // Link the painter to the printer
    {
        qWarning("Printer Error: Could not link painter to printer. ");
        return;
    }

    painter.setFont( QFont( "Courier New", 12, QFont::Bold ) );

    int pw = (int)( printer.pageRect( QPrinter::DevicePixel ).width() );
    int ph = (int)( printer.pageRect( QPrinter::DevicePixel ).height() );
    int y = 0;
    painter.drawText( 0, 0, pw, ph, Qt::AlignHCenter, "Station 40 - Youngsville Fire Department\n"
                     "Inventory Audit Report\n"  + QDate::currentDate().toString( "dddd the d of MMMM yyyy" ) );
    y = 80;
    if ( _pUI->chkCheckedItems->isChecked() )
    {
        painter.drawText( 0, y, pw, ph, Qt::AlignLeft, "Checked Items" );
        y += 20;

        for ( int i = 0; i < _pUI->tblCheckedIn->model()->rowCount(); i++ )
        {
            painter.drawText( 20, y, pw, ph, Qt::AlignLeft, _pUI->tblCheckedIn->model()->index( i, 1 ).data().toString() );
            y += 20;
        }
    }

    if ( _pUI->chkMissingItems->isChecked() )
    {
        painter.drawText( 0, y, pw, ph, Qt::AlignLeft, "Missing Items" );
        y += 20;
        for ( int i=0; i < _pUI->tblNotCheckedIn->model()->rowCount(); i++ )
        {
            painter.drawText( 20, y, pw, ph, Qt::AlignLeft, _pUI->tblNotCheckedIn->model()->index( i, 1 ).data().toString() );
            y += 20;
        }
    }
    painter.end();
}
Ejemplo n.º 2
0
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);
	}
}
Ejemplo n.º 3
0
  void
  TreeCanvas::print(void) {
    QPrinter printer;
    if (QPrintDialog(&printer, this).exec() == QDialog::Accepted) {
      QMutexLocker locker(&mutex);

      BoundingBox bb = root->getBoundingBox();
      QRect pageRect = printer.pageRect();
      double newXScale =
        static_cast<double>(pageRect.width()) / (bb.right - bb.left +
                                                 Layout::extent);
      double newYScale =
        static_cast<double>(pageRect.height()) /
                            (root->getShape()->depth() * Layout::dist_y +
                             2*Layout::extent);
      double printScale = std::min(newXScale, newYScale)*100;
      if (printScale<1.0)
        printScale = 1.0;
      if (printScale > 400.0)
        printScale = 400.0;
      printScale = printScale / 100.0;

      QPainter painter(&printer);
      painter.setRenderHint(QPainter::Antialiasing);
      painter.scale(printScale,printScale);
      painter.translate(xtrans, 0);
      QRect clip(0,0,0,0);
      DrawingCursor dc(root, *na, curBest, painter, clip, showCopies);
      PreorderNodeVisitor<DrawingCursor>(dc).run();
    }
  }
Ejemplo n.º 4
0
QRectF QPrinterProto::pageRect(QPrinter::Unit unit) const
{
  QPrinter *item = qscriptvalue_cast<QPrinter*>(thisObject());
  if (item)
    return item->pageRect(unit);
  return QRectF();
}
Ejemplo n.º 5
0
void CDiaryEdit::slotPrintPreview()
{
    CDiaryEditLock lock(this);
    collectData();

    QPrinter printer;
    QPrintDialog dialog(&printer, this);
    dialog.setWindowTitle(tr("Print Diary"));
    if (dialog.exec() != QDialog::Accepted)
        return;

    QTextDocument doc;
    QSizeF pageSize = printer.pageRect(QPrinter::DevicePixel).size();
    doc.setPageSize(pageSize);
    draw(doc);

    if(checkAddMap->isChecked())
    {
        QImage img;
        theMainWindow->getCanvas()->print(img, pageSize.toSize() - QSize(10,10));
        doc.rootFrame()->lastCursorPosition().insertImage(img);
    }
    doc.print(&printer);

    textEdit->clear();
    textEdit->document()->setTextWidth(textEdit->size().width() - 20);
    draw(*textEdit->document());
}
Ejemplo n.º 6
0
QRectF M_PagesizeMake( QPrinter::PageSize psize , bool landscape)
{
    QPrinter *print = new QPrinter(QPrinter::HighResolution);
    print->setFullPage(true);
    print->setPageSize(psize);
    if (landscape)
    {
        print->setOrientation(QPrinter::Landscape);
    }
    else
    {
        print->setOrientation(QPrinter::Portrait);
    }

    const QRectF pa = print->pageRect(QPrinter::Point);
    const qreal faktor = qMax(pa.width(),pa.height()) / qMin(pa.width(),pa.height());

    const qreal smaller = qMin(pa.width(),pa.height());
    const qreal biger = smaller * faktor;
    delete print;

    if ( landscape )
    {
        return QRectF(0,0,biger,smaller);
    }
    else
    {
        return QRectF(0,0,smaller,biger);
    }
}
Ejemplo n.º 7
0
void plotWindow::print()
{
  QPrinter printer;
  printer.setOrientation(QPrinter::Landscape);
  if (QPrintDialog(&printer).exec() == QDialog::Accepted)
  {
    QRectF sourceRect = plotdata.sceneRect();
    QPainter painter(&printer);
    painter.setRenderHint(QPainter::Antialiasing);
    plotdata.render(&painter, QRectF(printer.pageRect()), sourceRect);
  }
}
Ejemplo n.º 8
0
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);

}
Ejemplo n.º 9
0
void App::slotItemReadyForPrinting()
{
    QPrinter printer;
    QPrintDialog *dlg = new QPrintDialog(&printer, 0);
    if(dlg->exec() == QDialog::Accepted)
    {
        QRectF pageRect = printer.pageRect();
        QSize imgSize = m_printerImage->image().size();
        int totalHeight = imgSize.height();
        int yOffset = 0;

        qDebug() << "Page size:" << pageRect << ", image size:" << imgSize;
        QPainter painter(&printer);
        painter.setRenderHint(QPainter::Antialiasing, false);
        painter.setRenderHint(QPainter::SmoothPixmapTransform);

        QImage img = m_printerImage->image();
        int actualWidth = imgSize.width();

        // if the grabbed image is larger than the page, fit it to the page width
        if (pageRect.width() < imgSize.width())
        {
            img = m_printerImage->image().scaledToWidth(pageRect.width(), Qt::SmoothTransformation);
            actualWidth = pageRect.width();
        }

        // handle multi-page printing
        while(totalHeight > 0)
        {
            painter.drawImage(QPoint(0, 0), img, QRectF(0, yOffset, actualWidth, pageRect.height()));
            yOffset += pageRect.height();
            totalHeight -= pageRect.height();
            if (totalHeight > 0)
                printer.newPage();
        }

        painter.end();
    }

    m_printerImage.clear();
}
Ejemplo n.º 10
0
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();
    }
}
Ejemplo n.º 11
0
void DetailledPrintStyle::print( const KABC::Addressee::List &contacts, PrintProgress *progress )
{
  mPrintProgress = progress;

  progress->addMessage( i18n( "Setting up fonts and colors" ) );
  progress->setProgress( 0 );

  bool useKDEFonts;
  QFont font;
  QColor foreColor = Qt::black;
  QColor headerColor = Qt::white;
  bool useHeaderColor = true;
  QColor backColor = Qt::black;
  bool useBGColor;

  // save, always available defaults:
  QFont header = QFont("Helvetica", 12, QFont::Normal);
  QFont headlines = QFont("Helvetica", 12, QFont::Normal, true);
  QFont body = QFont("Helvetica", 12, QFont::Normal);
  QFont fixed = QFont("Courier", 12, QFont::Normal);
  QFont comment = QFont("Helvetica", 10, QFont::Normal);

  // store the configuration settings:
  KConfigGroup config = KGlobal::config()->group(ConfigSectionName);
  useKDEFonts = mPageAppearance->cbStandardFonts->isChecked();
  config.writeEntry( UseKDEFonts, useKDEFonts );

  // read the font and color selections from the wizard pages:
  useBGColor=mPageAppearance->cbBackgroundColor->isChecked();
  config.writeEntry( ColoredContactHeaders, useBGColor );

  // use colored contact headers, otherwise use plain black and white):
  if ( useBGColor ) {
    headerColor = mPageAppearance->kcbHeaderTextColor->color();
    backColor = mPageAppearance->kcbHeaderBGColor->color();
    config.writeEntry( ContactHeaderForeColor, headerColor );
    config.writeEntry( ContactHeaderBGColor, backColor );
  }

  if ( mPageAppearance->cbStandardFonts->isChecked() ) {
    QFont standard = KGlobalSettings::generalFont();
    header = standard;
    headlines = standard;
    body = standard;
    fixed = KGlobalSettings::fixedFont();
    comment = standard;
  } else {
    header.setFamily( mPageAppearance->kfcHeaderFont->currentText() );
    header.setPointSize( mPageAppearance->kisbHeaderFontSize->value() );
    config.writeEntry( HeaderFont, header );

    // headlines:
    headlines.setFamily( mPageAppearance->kfcHeadlineFont->currentText() );
    headlines.setPointSize( mPageAppearance->kisbHeadlineFontSize->value() );
    config.writeEntry( HeadlinesFont, headlines );

    // body:
    body.setFamily( mPageAppearance->kfcBodyFont->currentText() );
    body.setPointSize( mPageAppearance->kisbBodyFontSize->value() );
    config.writeEntry( BodyFont, body );

    // details:
    comment.setFamily( mPageAppearance->kfcDetailsFont->currentText() );
    comment.setPointSize( mPageAppearance->kisbDetailsFontSize->value() );
    config.writeEntry( DetailsFont, comment );

    // fixed:
    fixed.setFamily( mPageAppearance->kfcFixedFont->currentText() );
    fixed.setPointSize( mPageAppearance->kisbFixedFontSize->value() );
    config.writeEntry( FixedFont, fixed );
  }

  mPainter = new KABEntryPainter;
  mPainter->setForegroundColor( foreColor );
  mPainter->setHeaderColor( headerColor );
  mPainter->setBackgroundColor( backColor );
  mPainter->setUseHeaderColor( useHeaderColor );
  mPainter->setHeaderFont( header );
  mPainter->setHeadLineFont( headlines );
  mPainter->setBodyFont( body );
  mPainter->setFixedFont( fixed );
  mPainter->setCommentFont( comment );
  // Printing "Work Address:" / "Telephones:" headlines adds
  // no interesting information and just take space.
  // So I added this setter, but I leave it true by default because
  // otherwise the indenting looks a bit weird -- ## TODO.
  mPainter->setPrintHeadLines( true ); // TODO a checkbox for it

  QPrinter *printer = wizard()->printer();

  progress->addMessage( i18n( "Setting up margins and spacing" ) );
  int marginTop = 0,
      marginLeft = 64, // to allow stapling, need refinement with two-side prints
      marginRight = 0,
      marginBottom = 0;

  register int left, top, width, height;

  QPainter painter( printer );

  left = qMax( printer->pageRect().left() - printer->paperRect().left(), marginLeft );
  top = qMax( printer->pageRect().top() - printer->paperRect().top(), marginTop );
  width = printer->width() - left - qMax( printer->paperRect().right() - printer->pageRect().right(), marginRight );
  height = printer->height() - top - qMax( printer->paperRect().bottom() - printer->pageRect().bottom(), marginBottom );

  printer->setFullPage( true ); // use whole page
  painter.setViewport( left, top, width, height );
  progress->addMessage( i18n( "Printing" ) );

  printEntries( contacts, printer, &painter,
                QRect( 0, 0, printer->width(), printer->height() ) );

  progress->addMessage( i18n( "Done" ) );

  config.sync();
}
Ejemplo n.º 12
0
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);
			}
		}
}
Ejemplo n.º 13
0
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("");
}
Ejemplo n.º 14
0
int Printer::pageRect(lua_State * L) // const : QRect 
{
	QPrinter* lhs = ValueBinding<MyQPrinter>::check( L, 1 );
	*ValueBinding<QRectF>::create( L ) = lhs->pageRect();
	return 1; 
}
Ejemplo n.º 15
0
void SceneImageExporter::printScene(QGraphicsScene *scene, QPrinter& printer,
                                    QString fileName, QString documentName,
                                    int printingFlags)
{

    if (!fileName.isEmpty() && fileName != "" && fileName.endsWith(".pdf",Qt::CaseInsensitive))
    {
        printer.setOutputFormat(QPrinter::PdfFormat);
        printer.setOutputFileName(fileName);
    }
    else {
        //set page margins if I have to print on paper.
        printer.setPageMargins(10,10,10,10,QPrinter::Millimeter);
    }


    QPainter painter(&printer);

    QRectF sceneRect = scene->sceneRect();
    double sceneRatio = scene->sceneRect().width()/scene->sceneRect().height();
    qreal left,top,right,bottom;
    printer.getPageMargins(&left,&top,&right,&bottom,QPrinter::DevicePixel);
    QRect pageRect = QRect(
            printer.pageRect().top()+top,
            printer.pageRect().left()+left,
            printer.pageRect().width()-(left+right),
            printer.pageRect().height()-(top+bottom));

    int xSize, ySize, dxSize, dySize, xPages, yPages;
    double fWidth, fHeight, fHeightStep, fWidthStep;
    double pageRectRatio = (double)pageRect.width()/(double)pageRect.height();

    xSize = (int)((double)(3*pageRect.width()) * 1.0);
    ySize = (int)((double)(3*pageRect.height()) * .9);
    dxSize = (int)((double)(3*pageRect.width()) * .05);
    dySize = (int)((double)(3*pageRect.height()) * .05);

    xPages = 1+ (((int)sceneRect.width()) / xSize);
    yPages = 1+ (((int)sceneRect.height()) / ySize);

    if (SIEOptions::ScaleToSceneHeight(printingFlags)) {
        yPages = 1;
        xPages = 1+(int)( (double)yPages *sceneRatio);
        ySize = (int) ((double)scene->sceneRect().height()*.9);
        xSize = (int) ( (double)ySize * pageRectRatio);
        dySize = (int) (.05 * (double)scene->sceneRect().height()*.9);
        dxSize = (int) ( .05 *(double)ySize * pageRectRatio);

    }

    if (SIEOptions::ScaleToSceneWidth(printingFlags)) {
        xPages = 1;
        yPages = 1+(int)( (double)yPages / sceneRatio);
    }


    fWidth = 1.0* (double)pageRect.width();
    fHeight = .9* (double)pageRect.height();
    fHeightStep = .15* (double)pageRect.height();
    fWidthStep = fHeightStep * sceneRatio;

    bool bNewPage = false;
    double fWidth2 = fWidth * .9;
    double fHeight2 = fHeight * .9;

    QPainterPath path;
    QRectF rectOuter;
    rectOuter.setLeft((double)pageRect.left());
    rectOuter.setTop((double)pageRect.top());
    rectOuter.setWidth(fWidth2);
    rectOuter.setHeight(fHeight2);

    path.addRect(rectOuter);

    QRectF rectInner(rectOuter);
    rectInner.setTopLeft(QPointF(
            rectInner.left()+fWidth2/20,
            rectInner.top()+fHeight2/20));
    rectInner.setSize(QSizeF(fWidth2*.9,fHeight2*.9));
    path.addRect(rectInner);


    painter.begin(&printer);

    QBrush shadowBrush = QBrush(QColor(192,192,192,64));
    QBrush transparent = QBrush(QColor(192,192,192,16));
    //QPen pen = QPen(QColor (65,65,65,192));
    QPen pen = QPen(QColor (255,0,0,192));
    QFont font = QFont("Droid Sans");
    font.setBold(true);
    font.setPointSizeF(16.0);

    QFont fontb = QFont("Droid Sans");
    fontb.setBold(false);
    fontb.setPointSizeF(11.0);


    //double fh = fHeightStep / yPages;
    //double fw = fWidthStep / xPages;

    double tinyRectXRatio = fWidthStep / scene->sceneRect().width();
    double tinyRectYRatio = fHeightStep / scene->sceneRect().height();

    int nCur = 0;
    int nMax = yPages*xPages;

    for (int y = 0; y < yPages; y++) {
        for (int x = 0; x < xPages; x++) {
            nCur = (y*xPages)+(x+1);
            if (bNewPage)
                printer.newPage();
            else
                bNewPage = true;

            QRectF targetRect = QRectF((double)pageRect.left(),(double)pageRect.top(),fWidth2,fHeight2);

            QRectF sourceRect = QRectF (
                    (double)(x*xSize)+sceneRect.left()-(double)dxSize,
                    (double)(y*ySize)+sceneRect.top()-(double)dySize,
                    (double)(xSize)+2*(double)dxSize,
                    (double)(ySize)+2*(double)dySize);

            QRectF targetRect2 = QRectF(
                    (double)targetRect.left()+10,
                    (double)targetRect.top()+ fHeight2+10,
                    fWidthStep,
                    fHeightStep);

            QRectF tinyRect;
            tinyRect.setLeft((sourceRect.left()-sceneRect.left()) * tinyRectXRatio+targetRect2.left());
            tinyRect.setTop((sourceRect.top()-sceneRect.top()) * tinyRectYRatio+ targetRect2.top());
            tinyRect.setWidth(sourceRect.width()*tinyRectXRatio);
            tinyRect.setHeight(sourceRect.height()*tinyRectYRatio);


            scene->render(&painter,targetRect, sourceRect);
            painter.setPen(pen);
            painter.setBrush(transparent);
            painter.drawRect(targetRect2);

            scene->render(&painter,targetRect2, scene->sceneRect(), Qt::IgnoreAspectRatio);
            painter.setPen(pen);
            painter.setBrush(shadowBrush);
            painter.drawPath(path);
            painter.drawRect(tinyRect);

            QFontMetricsF metrics(font);

            int nDelta = 0;
            painter.setFont(font);
            painter.setBrush(QBrush(QColor("black")));
            painter.drawText(
                    targetRect2.left()+fWidthStep+10,
                    targetRect2.top()+metrics.height(),
                    documentName);

            nDelta+= (int)metrics.height()+10;

            painter.setFont(fontb);
            QFontMetricsF metricsb(fontb);
            nDelta+= (int)metricsb.height();
            QString txt = QString().sprintf("Folio [%d,%d] -- page %d of %d",x,y,nCur, nMax);
            painter.drawText(
                    targetRect2.left()+fWidthStep+10,
                    targetRect2.top()+nDelta,
                    txt);


        }
    }
    painter.end();
}
Ejemplo n.º 16
0
void MultiLayer::printAllLayers(QPainter *painter) {
  if (!painter) return;

  QPrinter *printer = (QPrinter *)painter->device();
  QRect paperRect = ((QPrinter *)painter->device())->paperRect();
  QRect canvasRect = canvas->rect();
  QRect pageRect = printer->pageRect();
  QRect cr = canvasRect;  // cropmarks rectangle

  if (d_scale_on_print) {
    int margin = (int)((1 / 2.54) * printer->logicalDpiY());  // 1 cm margins
    double scaleFactorX =
        (double)(paperRect.width() - 2 * margin) / (double)canvasRect.width();
    double scaleFactorY =
        (double)(paperRect.height() - 2 * margin) / (double)canvasRect.height();

    if (d_print_cropmarks) {
      cr.moveTo(QPoint(margin + int(cr.x() * scaleFactorX),
                       margin + int(cr.y() * scaleFactorY)));
      cr.setWidth(int(cr.width() * scaleFactorX));
      cr.setHeight(int(cr.height() * scaleFactorX));
    }

    for (int i = 0; i < (int)graphsList.count(); i++) {
      Graph *gr = (Graph *)graphsList.at(i);
      Plot *myPlot = gr->plotWidget();

      QPoint pos = gr->pos();
      pos = QPoint(margin + int(pos.x() * scaleFactorX),
                   margin + int(pos.y() * scaleFactorY));

      int width = int(myPlot->frameGeometry().width() * scaleFactorX);
      int height = int(myPlot->frameGeometry().height() * scaleFactorY);

      gr->print(painter, QRect(pos, QSize(width, height)));
    }
  } else {
    int x_margin = (pageRect.width() - canvasRect.width()) / 2;
    int y_margin = (pageRect.height() - canvasRect.height()) / 2;

    if (d_print_cropmarks) cr.moveTo(x_margin, y_margin);

    for (int i = 0; i < (int)graphsList.count(); i++) {
      Graph *gr = (Graph *)graphsList.at(i);
      Plot *myPlot = (Plot *)gr->plotWidget();

      QPoint pos = gr->pos();
      pos = QPoint(x_margin + pos.x(), y_margin + pos.y());
      gr->print(painter, QRect(pos, myPlot->size()));
    }
  }
  if (d_print_cropmarks) {
    cr.addCoords(-1, -1, 2, 2);
    painter->save();
    painter->setPen(QPen(QColor(Qt::black), 0.5, Qt::DashLine));
    painter->drawLine(paperRect.left(), cr.top(), paperRect.right(), cr.top());
    painter->drawLine(paperRect.left(), cr.bottom(), paperRect.right(),
                      cr.bottom());
    painter->drawLine(cr.left(), paperRect.top(), cr.left(),
                      paperRect.bottom());
    painter->drawLine(cr.right(), paperRect.top(), cr.right(),
                      paperRect.bottom());
    painter->restore();
  }
}
Ejemplo n.º 17
0
void StitchLibraryUi::printStitchSet()
{
    //FIXME: this only prints the visible part of the widget.
    QPrinter printer;
    QPrintDialog dialog(&printer, this);
    if(dialog.exec() != QDialog::Accepted)
        return;

    ui->listView->setWordWrap(true);
    ui->listView->setTextElideMode(Qt::ElideNone);
    const int rows = ui->listView->model()->rowCount();
    ui->listView->resizeRowsToContents();
    ui->listView->resizeColumnsToContents();

    // calculate the total width/height table would need without scaling
    double totalWidth = 0.0;   
    double totalHeight = 0.0;
    QList<int> widths;
    widths << 0 << 0 << 0;

    for (int r = 0; r < rows; ++r) {
        totalHeight += ui->listView->rowHeight(r);
        for (int c = 0; c < 3; ++c) {
            int temp = ui->listView->columnWidth(c);
            if(temp > widths.at(c))
                widths[c] = temp;
        }
    }

    foreach(int w, widths)
        totalWidth += w;


    //QSizeF size = QSize(totalWidth, totalHeight);
    //printer.setPaperSize(size, QPrinter::Point);
  
    QPainter p;
    p.begin(&printer);

    int rowHeight = 35;
    // paint cells
    for (int r = 0; r < rows; ++r) {

        if(rowHeight + ui->listView->rowHeight(r) > (printer.pageRect().height() - 35)) {
            printer.newPage();
            rowHeight = 35;
        }

        int startX = 0;
        for (int c = 0; c < 3; ++c) {
            QModelIndex idx = ui->listView->model()->index(r, c);
            QStyleOptionViewItem option;// = ui->listView->viewOptions();
            option.palette.setColor(QPalette::Text, QColor(Qt::black));
            option.rect.setTop(rowHeight);
            option.rect.setLeft(startX + 35);
            option.rect.setHeight(ui->listView->visualRect(idx).height());
            //FIXME: this shouldn't be hard coded but oh well
            option.rect.setWidth(widths[c] +100);
            ui->listView->itemDelegate()->paint(&p, option, idx);
            startX += widths[c];
        }

        rowHeight += ui->listView->rowHeight(r);
    }
    
    p.end();
}
Ejemplo n.º 18
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);
 }
}
Ejemplo n.º 19
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 ();
}
Ejemplo n.º 20
0
void MainWindow::printFile()
{
  GRPrintPagesDlg pagesdlg;
  if ( pagesdlg.exec() != QDialog::Accepted )
    return;

  int rows = pagesdlg.rows();
  int columns = pagesdlg.columns();

  QPrintDialog pr;
  if ( pr.exec() == QDialog::Accepted )
  {
    QPrinter *qp = pr.printer();

    int pwidth = qp->pageRect().width();
    int pheight = qp->pageRect().height();

    int npages = rows * columns;

    int gwidth = columns * pwidth, gheight = rows * pheight;

    QImage img(gwidth, gheight, QImage::Format_RGB444);

    if ( img.isNull() )
      return;

    // render graph

    QPainter gpaint;
    gpaint.begin(&img);

    gpaint.fillRect(img.rect(), Qt::white);

    QFont f("courier", 12);
    gpaint.setFont(f);

    QRect text_rect = gpaint.fontMetrics().boundingRect(G_title);
    int x = (gwidth - text_rect.width()) / 2;
    gpaint.drawText(x, text_rect.height(), G_title);

    PaintStruct ps;
    ps.p = &gpaint;
    ps.border = 60;
    set_drawing_rectangle(gwidth-120, gheight-120);
    display_complete_graph();
    draw_graph(draw_line, draw_rect, draw_poly, &ps);

    gpaint.end();

    // copy to pages

    QPainter prpaint;
    prpaint.begin(qp);

    QRect src;
    QRect dst(0, 0, pwidth, pheight);
    for ( int page = 0, col = 0, row = 0; page < npages; ++page )
    {
      src.setLeft(col*pwidth);
      src.setTop(row*pheight);
      src.setWidth(pwidth);
      src.setHeight(pheight);
      prpaint.drawImage(QPoint(0, 0), img, src);

      // next
      if ( page < npages - 1 )
        qp->newPage();

      if ( col < columns - 1 )
        ++col;
      else
      {
        ++row;
        col = 0;
      }
    }

    prpaint.end();

    //this will reset the drawing rectangle to the canvas values
    canvas->viewport()->repaint();
    display_complete_graph();
  }
}
Ejemplo n.º 21
0
void PrintTool::print()
{
    const QString processTitle = i18nc( "@title:window", "Print Byte Array %1", mDocument->title() );

    QPrinter printer;

//     LayoutDialogPage* layoutPage = new LayoutDialogPage();
    QList<QWidget*> customDialogPages;
//     customDialogPages << layoutPage;
    QPrintDialog *printDialog = new QPrintDialog( &printer, 0 );
    // Disable PrintPageRange, this tells Qt we can't do client-side page selection,
    // so it will try do server-side page selection if supported
    printDialog->setOption(QPrintDialog::PrintPageRange, false);
//    printDialog->setOptionTabs(customDialogPages);

    printDialog->setWindowTitle( processTitle );
    if( printDialog->exec() )
    {
        QString creator = QString::fromLatin1( "Print Plugin for Okteta " ); // no i18n(), keep space at end as separator
//         creator += KDEUTILS_VERSION_STRING; // TODO: change to OKTETA_VERSION_STRING
        printer.setCreator( creator );

        FramesToPaperPrinter framesPrinter;
        framesPrinter.setPaperRect( printer.paperRect() );
        framesPrinter.setPageRect( printer.pageRect() );
        printer.setFullPage( true );


        PrintInfo info;
        const QRect pageRect = framesPrinter.pageRect();
        const int left = pageRect.left();
        const int width = pageRect.width();

        HeaderFooterFrameRenderer *headerFrameRenderer = new HeaderFooterFrameRenderer( &info );
        headerFrameRenderer->setTexts( QStringLiteral("%d"),
                                       QStringLiteral("%f"),
                                       i18nc("in the header of the printed page, e.g. Page 2 of 20","Page %p of %P") );
        headerFrameRenderer->setWidth( width );
        headerFrameRenderer->setPos( pageRect.topLeft() );

        HeaderFooterFrameRenderer *footerFrameRenderer = new HeaderFooterFrameRenderer( &info );
        footerFrameRenderer->setTexts( i18nc("in the footer of the printed page, e.g. Printed by: Joe User",
                                             "Printed by: %U"),
                                       QString(),
                                       QStringLiteral("%F") );
        footerFrameRenderer->setWidth( width );
        const int footerTop = pageRect.bottom() - footerFrameRenderer->height();
        footerFrameRenderer->setPos( left, footerTop );

        const int contentHeight = pageRect.height() - footerFrameRenderer->height() - headerFrameRenderer->height();
        const int contentTop = pageRect.top() + headerFrameRenderer->height();
        ByteArrayFrameRenderer *byteArrayFrameRenderer = new ByteArrayFrameRenderer;
        byteArrayFrameRenderer->setPos( left, contentTop );
        byteArrayFrameRenderer->setWidth( width );
        byteArrayFrameRenderer->setHeight( contentHeight );

        Okteta::AddressRange range = mByteArrayView->selection();
        if( ! range.isValid() )
            range.setByWidth( 0, mByteArrayModel->size() );
        byteArrayFrameRenderer->setByteArrayModel( mByteArrayModel, range.start(), range.width() );

        // TODO: use noOfBytesPerLine of view, scale resolution down if it does not fit the page
        const int noOfBytesPerLine = mByteArrayView->noOfBytesPerLine();
//         byteArrayFrameRenderer->setNoOfBytesPerLine( mByteArrayView->noOfBytesPerLine() );

        const Okteta::Address startOffset = mByteArrayView->startOffset() + range.start();
        const int line = startOffset / noOfBytesPerLine;
        const Okteta::Address firstLineOffset = mByteArrayView->firstLineOffset() + line*noOfBytesPerLine;
        byteArrayFrameRenderer->setFirstLineOffset( firstLineOffset );
        byteArrayFrameRenderer->setStartOffset( startOffset );

        byteArrayFrameRenderer->setCharCoding( mByteArrayView->charCodingName() );
        byteArrayFrameRenderer->setBufferSpacing( mByteArrayView->byteSpacingWidth(),
                                                  mByteArrayView->noOfGroupedBytes(),
                                                  mByteArrayView->groupSpacingWidth() );
        byteArrayFrameRenderer->setBinaryGapWidth( mByteArrayView->binaryGapWidth() );

        byteArrayFrameRenderer->setValueCoding( (Okteta::ValueCoding)mByteArrayView->valueCoding() );
        byteArrayFrameRenderer->setShowsNonprinting( mByteArrayView->showsNonprinting() );
        byteArrayFrameRenderer->setSubstituteChar( mByteArrayView->substituteChar() );
        byteArrayFrameRenderer->setUndefinedChar( mByteArrayView->undefinedChar() );
        byteArrayFrameRenderer->showByteArrayColumns( mByteArrayView->visibleByteArrayCodings() );

//     if( !confirmPrintPageNumber( byteArrayFrameRenderer->framesCount()) )
//         return;

        framesPrinter.addFrameRenderer( headerFrameRenderer );
        framesPrinter.addFrameRenderer( byteArrayFrameRenderer );
        framesPrinter.addFrameRenderer( footerFrameRenderer );

        info.setNoOfPages( byteArrayFrameRenderer->framesCount() );
        AbstractModelSynchronizer* synchronizer = mDocument->synchronizer();
        if (synchronizer) {
            info.setUrl( synchronizer->url() );
        }

        QApplication::setOverrideCursor( Qt::WaitCursor );

        PrintJob *printJob = new PrintJob( &framesPrinter, 0, byteArrayFrameRenderer->framesCount()-1, &printer );
        const bool success = printJob->exec();

        QApplication::restoreOverrideCursor();

        if( ! success )
        {
            const QString message = i18nc( "@info","Could not print." );

            KMessageBox::sorry( 0, message, processTitle );
        }
    }

    delete printDialog;
}