예제 #1
0
  /*!
   * \author Anders Fernström
   * \date 2005-12-19
   *
   * \brief The class constructor
   *
   * 2006-03-03 AF, Updated function so cells are printed in tables,
   * so chapter numbers can be added to the left of the text. This
   * change remade large part of this function (and the rest of the
   * class).
   */
  PrinterVisitor::PrinterVisitor( QTextDocument* doc, QPrinter* printer )
    : ignore_(false), firstChild_(true), closedCell_(0), currentTableRow_(0), printer_(printer)
  {
    printEditor_ = new QTextEdit();
    printEditor_->setDocument( doc );



    // set table format
    QTextTableFormat tableFormat;
    tableFormat.setBorder( 0 );
    tableFormat.setColumns( 2 );
    tableFormat.setCellPadding( 2 );

    // do not put the constraints on the columns. If we don't have chapter numbers we want to use the full space.
//    QVector<QTextLength> constraints;
//        constraints << QTextLength(QTextLength::PercentageLength, 20)
//                    << QTextLength(QTextLength::PercentageLength, 80);
//        tableFormat.setColumnWidthConstraints(constraints);

    // insert the table
    QTextCursor cursor = printEditor_->textCursor();
    table_ = cursor.insertTable(1, 2, tableFormat);

  }
/*!
    \fn void QTextTable::setFormat(const QTextTableFormat &format)

    Sets the table's \a format.

    \sa format()
*/
void QTextTable::setFormat(const QTextTableFormat &format)
{
    QTextTableFormat fmt = format;
    // don't try to change the number of table columns from here
    fmt.setColumns(columns());
    QTextObject::setFormat(fmt);
}
예제 #3
0
  // TEXTCELL
  void PrinterVisitor::visitTextCellNodeBefore(TextCell *node)
  {
    if( !ignore_ || firstChild_ )
    {
      ++currentTableRow_;
      table_->insertRows( currentTableRow_, 1 );

      // first column
      QTextTableCell tableCell( table_->cellAt( currentTableRow_, 0 ) );
      if( tableCell.isValid() )
      {
        if( !node->ChapterCounterHtml().isNull() )
        {
          QTextCursor cursor( tableCell.firstCursorPosition() );
          cursor.insertFragment( QTextDocumentFragment::fromHtml(
            node->ChapterCounterHtml() ));

        }
      }

      // second column
      tableCell = table_->cellAt( currentTableRow_, 1 );
      if( tableCell.isValid() )
      {
        QTextCursor cursor( tableCell.firstCursorPosition() );

        if( node->isViewExpression() )
        {
          //view expression table
          QTextTableFormat tableFormatExpression;
          tableFormatExpression.setBorder( 0 );
          tableFormatExpression.setColumns( 1 );
          tableFormatExpression.setCellPadding( 2 );
//          tableFormatExpression.setBackground( QColor(235, 235, 220) ); // 180, 180, 180
          tableFormatExpression.setBackground( QColor(235, 0, 0) ); // 180, 180, 180

          QVector<QTextLength> constraints;
          constraints << QTextLength(QTextLength::PercentageLength, 100);
          tableFormatExpression.setColumnWidthConstraints(constraints);

          cursor.insertTable( 1, 1, tableFormatExpression );
          // QMessageBox::information(0,"uu2", node->text());

          QString html = node->textHtml();
          cursor.insertFragment( QTextDocumentFragment::fromHtml( html ));
        }
        else
        {
          QString html = node->textHtml();
          html.remove( "file:///" );
          printEditor_->document()->setTextWidth(700);
          cursor.insertFragment(QTextDocumentFragment::fromHtml( html ));
          // QMessageBox::information(0, "uu3", node->text());
        }
      }

      if( firstChild_ )
        firstChild_ = false;
    }
  }
예제 #4
0
파일: qtexttable.cpp 프로젝트: Fale/qtmoko
/*!
    \fn void QTextTable::insertColumns(int index, int columns)

    Inserts a number of \a columns before the column with the specified \a index.

    \sa insertRows() resize() removeRows() removeColumns() appendRows() appendColumns()
*/
void QTextTable::insertColumns(int pos, int num)
{
    Q_D(QTextTable);
    if (num <= 0)
	return;

    if (d->dirty)
        d->update();

    if (pos > d->nCols || pos < 0)
        pos = d->nCols;

//     qDebug() << "-------- insertCols" << pos << num;
    QTextDocumentPrivate *p = d->pieceTable;
    QTextFormatCollection *c = p->formatCollection();
    p->beginEditBlock();

    for (int i = 0; i < d->nRows; ++i) {
        int cell;
        if (i == d->nRows - 1 && pos == d->nCols)
            cell = d->fragment_end;
        else
            cell = d->grid[i*d->nCols + pos];
        QTextDocumentPrivate::FragmentIterator it(&p->fragmentMap(), cell);
        QTextCharFormat fmt = c->charFormat(it->format);
        if (pos > 0 && pos < d->nCols && cell == d->grid[i*d->nCols + pos - 1]) {
            // cell spans the insertion place, extend it
            fmt.setTableCellColumnSpan(fmt.tableCellColumnSpan() + num);
            p->setCharFormat(it.position(), 1, fmt);
        } else {
            fmt.setTableCellRowSpan(1);
            fmt.setTableCellColumnSpan(1);
            Q_ASSERT(fmt.objectIndex() == objectIndex());
            int position = it.position();
            int cfmt = p->formatCollection()->indexForFormat(fmt);
            int bfmt = p->formatCollection()->indexForFormat(QTextBlockFormat());
            for (int i = 0; i < num; ++i)
                p->insertBlock(QTextBeginningOfFrame, position, bfmt, cfmt, QTextUndoCommand::MoveCursor);
        }
    }

    QTextTableFormat tfmt = format();
    tfmt.setColumns(tfmt.columns()+num);
    QVector<QTextLength> columnWidths = tfmt.columnWidthConstraints();
    if (! columnWidths.isEmpty()) {
        for (int i = num; i > 0; --i)
            columnWidths.insert(pos, columnWidths[qMax(0, pos-1)]);
    }
    tfmt.setColumnWidthConstraints (columnWidths);
    QTextObject::setFormat(tfmt);

//     qDebug() << "-------- end insertCols" << pos << num;
    p->endEditBlock();
}
/*!
    \fn void QTextTable::removeColumns(int index, int columns)

    Removes a number of \a columns starting with the column at the specified
    \a index.

    \sa insertRows() insertColumns() removeRows() resize()
*/
void QTextTable::removeColumns(int pos, int num)
{
    Q_D(QTextTable);
//     qDebug() << "-------- removeCols" << pos << num;

    if (num <= 0 || pos < 0)
	return;
    if (d->dirty)
        d->update();
    if (pos >= d->nCols)
        return;
    if (pos + num > d->nCols)
        pos = d->nCols - num;

    QTextDocumentPrivate *p = d->pieceTable;
    QTextFormatCollection *collection = p->formatCollection();
    p->beginEditBlock();

    // delete whole table?
    if (pos == 0 && num == d->nCols) {
        const int pos = p->fragmentMap().position(d->fragment_start);
        p->remove(pos, p->fragmentMap().position(d->fragment_end) - pos + 1);
        p->endEditBlock();
        return;
    }

    for (int r = 0; r < d->nRows; ++r) {
        for (int c = pos; c < pos + num; ++c) {
            int cell = d->grid[r*d->nCols + c];
            QTextDocumentPrivate::FragmentIterator it(&p->fragmentMap(), cell);
            QTextCharFormat fmt = collection->charFormat(it->format);
            int span = fmt.tableCellColumnSpan();
            if (span > 1) {
                fmt.setTableCellColumnSpan(span - 1);
                p->setCharFormat(it.position(), 1, fmt);
            } else {
                // remove cell
                int index = d->cells.indexOf(cell) + 1;
                int f_end = index < d->cells.size() ? d->cells.at(index) : d->fragment_end;
                p->remove(it.position(), p->fragmentMap().position(f_end) - it.position());
            }
        }
    }

    QTextTableFormat tfmt = format();
    tfmt.setColumns(tfmt.columns()-num);
    QTextObject::setFormat(tfmt);

    p->endEditBlock();
//     qDebug() << "-------- end removeCols" << pos << num;
}
예제 #6
0
QTextTable *QTextTablePrivate::createTable(QTextDocumentPrivate *pieceTable, int pos, int rows, int cols, const QTextTableFormat &tableFormat)
{
    QTextTableFormat fmt = tableFormat;
    fmt.setColumns(cols);
    QTextTable *table = qobject_cast<QTextTable *>(pieceTable->createObject(fmt));
    Q_ASSERT(table);

    pieceTable->beginEditBlock();

//     qDebug("---> createTable: rows=%d, cols=%d at %d", rows, cols, pos);
    // add block after table
    QTextCharFormat charFmt;
    charFmt.setObjectIndex(table->objectIndex());
    charFmt.setObjectType(QTextFormat::TableCellObject);


    int charIdx = pieceTable->formatCollection()->indexForFormat(charFmt);
    int cellIdx = pieceTable->formatCollection()->indexForFormat(QTextBlockFormat());

    QTextTablePrivate *d = table->d_func();
    d->blockFragmentUpdates = true;

    d->fragment_start = pieceTable->insertBlock(QTextBeginningOfFrame, pos, cellIdx, charIdx);
    d->cells.append(d->fragment_start);
    ++pos;

    for (int i = 1; i < rows*cols; ++i) {
        d->cells.append(pieceTable->insertBlock(QTextBeginningOfFrame, pos, cellIdx, charIdx));
//      qDebug("      addCell at %d", pos);
        ++pos;
    }

    d->fragment_end = pieceTable->insertBlock(QTextEndOfFrame, pos, cellIdx, charIdx);
//  qDebug("      addEOR at %d", pos);
    ++pos;

    d->blockFragmentUpdates = false;
    d->dirty = true;

    pieceTable->endEditBlock();

    return table;
}
예제 #7
0
  /*!
   * \author Anders Fernström
   * \date 2005-12-19
   *
   * \brief The class constructor
   *
   * 2006-03-03 AF, Updated function so cells are printed in tables,
   * so chapter numbers can be added to the left of the text. This
   * change remade large part of this function (and the rest of the
   * class).
   */
  PrinterVisitor::PrinterVisitor( QTextDocument* doc, QPrinter* printer )
    : ignore_(false), firstChild_(true), closedCell_(0), currentTableRow_(0), printer_(printer)
  {
    printEditor_ = new QTextEdit();
    printEditor_->setDocument( doc );



    // set table format
    QTextTableFormat tableFormat;
    tableFormat.setBorder( 0 );
    tableFormat.setColumns( 2 );
    tableFormat.setCellPadding( 5 );

    QVector<QTextLength> constraints;
        constraints << QTextLength(QTextLength::FixedLength, 50)
                    << QTextLength(QTextLength::VariableLength, 620);
        tableFormat.setColumnWidthConstraints(constraints);

    // insert the table
    QTextCursor cursor = printEditor_->textCursor();
    table_ = cursor.insertTable(1, 2, tableFormat);

  }
예제 #8
0
void QTextCopyHelper::copy()
{
    if (cursor.hasComplexSelection()) {
        QTextTable *table = cursor.currentTable();
        int row_start, col_start, num_rows, num_cols;
        cursor.selectedTableCells(&row_start, &num_rows, &col_start, &num_cols);

        QTextTableFormat tableFormat = table->format();
        tableFormat.setColumns(num_cols);
        tableFormat.clearColumnWidthConstraints();
        const int objectIndex = dst->formatCollection()->createObjectIndex(tableFormat);

        Q_ASSERT(row_start != -1);
        for (int r = row_start; r < row_start + num_rows; ++r) {
            for (int c = col_start; c < col_start + num_cols; ++c) {
                QTextTableCell cell = table->cellAt(r, c);
                const int rspan = cell.rowSpan();
                const int cspan = cell.columnSpan();
                if (rspan != 1) {
                    int cr = cell.row();
                    if (cr != r)
                        continue;
                }
                if (cspan != 1) {
                    int cc = cell.column();
                    if (cc != c)
                        continue;
                }

                // add the QTextBeginningOfFrame
                QTextCharFormat cellFormat = cell.format();
                if (r + rspan >= row_start + num_rows) {
                    cellFormat.setTableCellRowSpan(row_start + num_rows - r);
                }
                if (c + cspan >= col_start + num_cols) {
                    cellFormat.setTableCellColumnSpan(col_start + num_cols - c);
                }
                const int charFormatIndex = convertFormatIndex(cellFormat, objectIndex);

                int blockIdx = -2;
                const int cellPos = cell.firstPosition();
                QTextBlock block = src->blocksFind(cellPos);
                if (block.position() == cellPos) {
                    blockIdx = convertFormatIndex(block.blockFormat());
                }

                dst->insertBlock(QTextBeginningOfFrame, insertPos, blockIdx, charFormatIndex);
                ++insertPos;

                // nothing to add for empty cells
                if (cell.lastPosition() > cellPos) {
                    // add the contents
                    appendFragments(cellPos, cell.lastPosition());
                }
            }
        }

        // add end of table
        int end = table->lastPosition();
        appendFragment(end, end+1, objectIndex);
    } else {
        appendFragments(cursor.selectionStart(), cursor.selectionEnd());
    }
}
예제 #9
0
/*!
    \fn void QTextTable::removeColumns(int index, int columns)

    Removes a number of \a columns starting with the column at the specified
    \a index.

    \sa insertRows(), insertColumns(), removeRows(), resize(), appendRows(), appendColumns()
*/
void QTextTable::removeColumns(int pos, int num)
{
    Q_D(QTextTable);
//     qDebug() << "-------- removeCols" << pos << num;

    if (num <= 0 || pos < 0)
        return;
    if (d->dirty)
        d->update();
    if (pos >= d->nCols)
        return;
    if (pos + num > d->nCols)
        pos = d->nCols - num;

    QTextDocumentPrivate *p = d->pieceTable;
    QTextFormatCollection *collection = p->formatCollection();
    p->beginEditBlock();

    // delete whole table?
    if (pos == 0 && num == d->nCols) {
        const int pos = p->fragmentMap().position(d->fragment_start);
        p->remove(pos, p->fragmentMap().position(d->fragment_end) - pos + 1);
        p->endEditBlock();
        return;
    }

    p->aboutToRemoveCell(cellAt(0, pos).firstPosition(), cellAt(d->nRows - 1, pos + num - 1).lastPosition());

    QList<int> touchedCells;
    for (int r = 0; r < d->nRows; ++r) {
        for (int c = pos; c < pos + num; ++c) {
            int cell = d->grid[r*d->nCols + c];
            QTextDocumentPrivate::FragmentIterator it(&p->fragmentMap(), cell);
            QTextCharFormat fmt = collection->charFormat(it->format);
            int span = fmt.tableCellColumnSpan();
            if (touchedCells.contains(cell) && span <= 1)
                continue;
            touchedCells << cell;

            if (span > 1) {
                fmt.setTableCellColumnSpan(span - 1);
                p->setCharFormat(it.position(), 1, fmt);
            } else {
                // remove cell
                int index = d->cells.indexOf(cell) + 1;
                int f_end = index < d->cells.size() ? d->cells.at(index) : d->fragment_end;
                p->remove(it.position(), p->fragmentMap().position(f_end) - it.position());
            }
        }
    }

    QTextTableFormat tfmt = format();
    tfmt.setColumns(tfmt.columns()-num);
    QVector<QTextLength> columnWidths = tfmt.columnWidthConstraints();
    if (columnWidths.count() > pos) {
        columnWidths.remove(pos, num);
        tfmt.setColumnWidthConstraints (columnWidths);
    }
    QTextObject::setFormat(tfmt);

    p->endEditBlock();
//     qDebug() << "-------- end removeCols" << pos << num;
}
예제 #10
0
/*!
    \fn void QTextTable::insertColumns(int index, int columns)

    Inserts a number of \a columns before the column with the specified \a index.

    \sa insertRows(), resize(), removeRows(), removeColumns(), appendRows(), appendColumns()
*/
void QTextTable::insertColumns(int pos, int num)
{
    Q_D(QTextTable);
    if (num <= 0)
        return;

    if (d->dirty)
        d->update();

    if (pos > d->nCols || pos < 0)
        pos = d->nCols;

//     qDebug() << "-------- insertCols" << pos << num;
    QTextDocumentPrivate *p = d->pieceTable;
    QTextFormatCollection *c = p->formatCollection();
    p->beginEditBlock();

    QList<int> extendedSpans;
    for (int i = 0; i < d->nRows; ++i) {
        int cell;
        if (i == d->nRows - 1 && pos == d->nCols) {
            cell = d->fragment_end;
        } else {
            int logicalGridIndexBeforePosition = pos > 0
                                                 ? d->findCellIndex(d->grid[i*d->nCols + pos - 1])
                                                 : -1;

            // Search for the logical insertion point by skipping past cells which are not the first
            // cell in a rowspan. This means any cell for which the logical grid index is
            // less than the logical cell index of the cell before the insertion.
            int logicalGridIndex;
            int gridArrayOffset = i*d->nCols + pos;
            do {
                cell = d->grid[gridArrayOffset];
                logicalGridIndex = d->findCellIndex(cell);
                gridArrayOffset++;
            } while (logicalGridIndex < logicalGridIndexBeforePosition
                     && gridArrayOffset < d->nRows*d->nCols);

            if (logicalGridIndex < logicalGridIndexBeforePosition
                && gridArrayOffset == d->nRows*d->nCols)
                cell = d->fragment_end;
        }

        if (pos > 0 && pos < d->nCols && cell == d->grid[i*d->nCols + pos - 1]) {
            // cell spans the insertion place, extend it
            if (!extendedSpans.contains(cell)) {
                QTextDocumentPrivate::FragmentIterator it(&p->fragmentMap(), cell);
                QTextCharFormat fmt = c->charFormat(it->format);
                fmt.setTableCellColumnSpan(fmt.tableCellColumnSpan() + num);
                p->setCharFormat(it.position(), 1, fmt);
                d->dirty = true;
                extendedSpans << cell;
            }
        } else {
            /* If the next cell is spanned from the row above, we need to find the right position
            to insert to */
            if (i > 0 && pos < d->nCols && cell == d->grid[(i-1) * d->nCols + pos]) {
                int gridIndex = i*d->nCols + pos;
                const int gridEnd = d->nRows * d->nCols - 1;
                while (gridIndex < gridEnd && cell == d->grid[gridIndex]) {
                    ++gridIndex;
                }
                if (gridIndex == gridEnd)
                    cell = d->fragment_end;
                else
                    cell = d->grid[gridIndex];
            }
            QTextDocumentPrivate::FragmentIterator it(&p->fragmentMap(), cell);
            QTextCharFormat fmt = c->charFormat(it->format);
            fmt.setTableCellRowSpan(1);
            fmt.setTableCellColumnSpan(1);
            Q_ASSERT(fmt.objectIndex() == objectIndex());
            int position = it.position();
            int cfmt = p->formatCollection()->indexForFormat(fmt);
            int bfmt = p->formatCollection()->indexForFormat(QTextBlockFormat());
            for (int i = 0; i < num; ++i)
                p->insertBlock(QTextBeginningOfFrame, position, bfmt, cfmt, QTextUndoCommand::MoveCursor);
        }
    }

    QTextTableFormat tfmt = format();
    tfmt.setColumns(tfmt.columns()+num);
    QVector<QTextLength> columnWidths = tfmt.columnWidthConstraints();
    if (! columnWidths.isEmpty()) {
        for (int i = num; i > 0; --i)
            columnWidths.insert(pos, columnWidths[qMax(0, pos-1)]);
    }
    tfmt.setColumnWidthConstraints (columnWidths);
    QTextObject::setFormat(tfmt);

//     qDebug() << "-------- end insertCols" << pos << num;
    p->endEditBlock();
}
예제 #11
0
  void PrinterVisitor::visitLatexCellNodeBefore(LatexCell *node)
  {
    if( !ignore_ || firstChild_ )
    {

      ++currentTableRow_;
      table_->insertRows( currentTableRow_, 1 );

      // first column
      QTextTableCell tableCell( table_->cellAt( currentTableRow_, 0 ) );
      if( tableCell.isValid() )
      {
        if( !node->ChapterCounterHtml().isNull() )
        {
          QTextCursor cursor( tableCell.firstCursorPosition() );
          cursor.insertFragment( QTextDocumentFragment::fromHtml(
            node->ChapterCounterHtml() ));
        }
      }

      // second column
      tableCell = table_->cellAt( currentTableRow_, 1 );
      if( tableCell.isValid() )
      {
        QTextCursor cursor( tableCell.firstCursorPosition() );

        // input table
        QTextTableFormat tableFormatInput;
        tableFormatInput.setBorder( 0 );
        tableFormatInput.setMargin( 6 );
        tableFormatInput.setColumns( 1 );
        tableFormatInput.setCellPadding( 8 );
        tableFormatInput.setBackground( QColor(245, 245, 255) ); // 200, 200, 255
        QVector<QTextLength> constraints;
        constraints << QTextLength(QTextLength::PercentageLength, 100);
                tableFormatInput.setColumnWidthConstraints(constraints);
        cursor.insertTable( 1, 1, tableFormatInput );

        QString html = node->textHtml();
        html += "<br>";
        if( !node->isEvaluated() || node->isClosed() )
          html += "<br>";
        cursor.insertFragment( QTextDocumentFragment::fromHtml( html ));

        if( node->isEvaluated() && !node->isClosed() )
        {
          QTextTableFormat tableFormatOutput;
          tableFormatOutput.setBorder( 0 );
          tableFormatOutput.setMargin( 6 );
          tableFormatOutput.setColumns( 1 );
          tableFormatOutput.setCellPadding( 8 );
          QVector<QTextLength> constraints;
          constraints << QTextLength(QTextLength::PercentageLength, 100);
          tableFormatOutput.setColumnWidthConstraints(constraints);

          cursor = tableCell.lastCursorPosition();
          cursor.insertTable( 1, 1, tableFormatOutput );

          QString outputHtml( node->textOutputHtml() );
          outputHtml += "<br><br>";


          outputHtml.remove( "file:///" );
          cursor.insertFragment( QTextDocumentFragment::fromHtml( outputHtml ));
        }

      }

      if( firstChild_ )
        firstChild_ = false;
    }
  }
예제 #12
0
void CalcFrame::printCalc()
{
    const auto milkReception = m_mainWindow->database()->milkReception();

        if (!milkReception) {
            Utils::Main::showMsgIfDbNotChoosed(this);
            return;
        }
        DataWorker dw(m_mainWindow->database());
        try {
            dw.loadMilkReceptions(getWhereQuery());
        } catch (const QString &err) {
            QMessageBox::critical(this, tr("Расчеты"), tr("Произошла ошибка во время подгрузки данных: ") + err);
        }
        const auto deliverers = dw.getDeliverers().values();

        if (deliverers.isEmpty())
        {
            QMessageBox::information(this, tr("Печать"), tr("Отсутствуют данные для печати"));
            return;
        }

        const char f = 'f';
        int row = 0;
        const auto settings = m_mainWindow->getSettings();
        const auto printColumns = m_mainWindow->getSettings()->getPrint().columns;

        QStringList columns;
        for (int i = 0; i < printColumns.size(); ++i) {
            const auto &col = printColumns[i];
            if (col.isShow)
                columns.append(printColumns[i].display);
        }

        const int columnsCount = columns.size();
        if (columnsCount <= 0) {
            QMessageBox::information(this, tr("Печать сдачи молока"), tr("Не выбрана ни одна колонка для печати"));
            return;
        }

        const Settings::Column snCol = printColumns[Constants::PrintColumns::SerialNumber],
                delivNameCol = printColumns[Constants::PrintColumns::DeliverersName],
                litersCol = printColumns[Constants::PrintColumns::Liters],
                fatCol = printColumns[Constants::PrintColumns::Fat],
                proteinCol = printColumns[Constants::PrintColumns::Protein],
                fatUnitsCol = printColumns[Constants::PrintColumns::FatUnits],
                rankWeightCol = printColumns[Constants::PrintColumns::RankWeight],
                payCol = printColumns[Constants::PrintColumns::PayWithOutPrem],
                permiumCol = printColumns[Constants::PrintColumns::Premium],
                sumCol = printColumns[Constants::PrintColumns::Sum],
                signCol = printColumns[Constants::PrintColumns::Sign];

        auto itemToPrintRow = [&](const QString &delivName, const CalculatedItem::Data &item,
                const int rowPos = -1) -> QStringList
        {
            QStringList row;

            if (snCol.isShow)
                row.append(rowPos >= 0 ? QString::number(rowPos) : QString());
            if (delivNameCol.isShow)
                row.append(delivName);
            if (litersCol.isShow)
                row.append(QString::number(item.liters, f, litersCol.prec));
            if (fatCol.isShow)
                row.append(QString::number(item.fat, f, fatCol.prec));
            if (proteinCol.isShow)
                row.append(QString::number(item.protein, f, proteinCol.prec));
            if (fatUnitsCol.isShow)
                row.append(QString::number(item.fatUnits, f, fatCol.prec));
            if (rankWeightCol.isShow)
                row.append(QString::number(item.rankWeight, f, rankWeightCol.prec));
            if (payCol.isShow)
                row.append(QString::number(item.paymentWithOutPremium, f, payCol.prec));
            if (permiumCol.isShow)
                row.append(QString::number(item.premiumForFat, f, permiumCol.prec));
            if (sumCol.isShow)
                row.append(QString::number(floor(item.sum), f, sumCol.prec));
            if (signCol.isShow)
                row.append(QString());

            return row;
        };

        const auto &printSettings = settings->getPrint();

        QTextTableFormat tableFormat;
        tableFormat.setBorder(printSettings.tableBorderWidth);
        tableFormat.setBorderStyle(static_cast<QTextFrameFormat::BorderStyle>(printSettings.tableBorderStyle));
        tableFormat.setColumns(columnsCount);
        tableFormat.setAlignment(Qt::AlignHCenter);
        tableFormat.setWidth(QTextLength(QTextLength::VariableLength, 100));
        tableFormat.setBorderBrush(QBrush(printSettings.tableBorderColor));
        tableFormat.setCellSpacing(printSettings.cellSpacing);
        tableFormat.setCellPadding(printSettings.cellPadding);

        PrintTable print(columnsCount, tableFormat);
        {
            auto &textFormat = print.getTableBodyTextFormat();
            textFormat.setFont(printSettings.tableTextFont);
            textFormat.setForeground(QBrush(printSettings.tableTextColor));
        }
        {
            auto &textFormat = print.getTableHeadersFormat();
            textFormat.setFont(printSettings.tableHeaderFont);
            textFormat.setForeground(QBrush(printSettings.tableHeaderColor));
        }
        print.setHeaders(columns);

        CalculatedItem::Data allResult;
        for (const auto &deliverer: deliverers)
        {
            row++;

            const CalculatedItem::Data calcItem = deliverer->getCalculations();
            print.addRow(itemToPrintRow(deliverer->name(), calcItem, row));

            allResult += calcItem;
        }

        int mergeCount = 0;
        auto itemRow = itemToPrintRow("Итого", allResult, row);
        for (int i = 0; i < Constants::PrintColumns::Liters; i++) {
            const auto &col = printColumns[i];
            if (col.isShow)
                mergeCount++;
        }
        QTextCharFormat resultFormat;
        resultFormat.setFont(printSettings.tableResultFont);
        resultFormat.setForeground(QBrush(printSettings.tableResultColor));

        print.addRow(itemRow, resultFormat, mergeCount);

        auto &cursor = print.cursor();

        cursor.setPosition(0);

        QTextFrameFormat topFrameFormat;
        topFrameFormat.setPadding(4);
        cursor.insertFrame(topFrameFormat);

        QTextBlockFormat textBlockFormat;
        textBlockFormat.setBottomMargin(4);
        textBlockFormat.setAlignment(Qt::AlignLeft);

        QTextBlockFormat captionBlockFormat;
        captionBlockFormat.setAlignment(Qt::AlignCenter);
        cursor.setBlockFormat(textBlockFormat);

        QTextCharFormat textCharFormat;
        textCharFormat.setFont(printSettings.textFont);
        QTextCharFormat captionCharFormat;
        captionCharFormat.setFont(printSettings.captionTextFont);
        captionCharFormat.setForeground(QBrush(printSettings.captionColor));

        cursor.insertText(settings->getFirmName(), textCharFormat);
        cursor.insertBlock();

        cursor.setBlockFormat(captionBlockFormat);

        auto dateMin = QDate(), dateMax = QDate();

        if (isCalcByDate()) {
            dateMin = ui->dateEditFilterStart->date();
            dateMax = ui->dateEditFilterEnd->date();
        } else {
            dateMin = milkReception->getMinDeliveryDate();
            dateMax = milkReception->getMaxDeliveryDate();
        }

        const auto s = dateMax == dateMin ? tr("%1 число").arg(dateMin.toString(Constants::defaultDateFormat())) :
                                            tr("период с %1 по %2")
                                            .arg(dateMin.toString(Constants::defaultDateFormat()))
                                            .arg(dateMax.toString(Constants::defaultDateFormat()));

        cursor.insertText(QString(tr("Платежная ведомость №\n"
                                     "за сданное молоко\n"
                                     "за ") + s), captionCharFormat);
        cursor.insertBlock();
        cursor.setBlockFormat(textBlockFormat);

        cursor.insertText(tr("Населенный пункт: ") + m_mainWindow->getCurrentLocalityName(), textCharFormat);
        cursor.insertBlock();
        cursor.insertText(tr("Приемщик молока: ") + settings->getMilkInspector(), textCharFormat);
        cursor.insertBlock();

        cursor.movePosition(QTextCursor::End);

        QTextFrameFormat bottomFrameFormat;
        bottomFrameFormat.setPadding(4);
        cursor.insertFrame(bottomFrameFormat);

        cursor.setBlockFormat(textBlockFormat);

        const auto minMaxPrice = milkReception->getMinMaxPriceLiter(dateMin, dateMax);
        if (minMaxPrice.first > .0 && minMaxPrice.second > .0) {
            const QString minPrice = QString::number(minMaxPrice.first, f, 2),
                maxPrice = QString::number(minMaxPrice.second, f, 2);

            cursor.insertText(tr("Цена: %1").arg(minPrice == maxPrice ? minPrice : QString("%1 - %2")
                                                                        .arg(minPrice).arg(maxPrice)));
            cursor.insertBlock();
        }
        cursor.insertText(tr("Деньги в сумме: "), textCharFormat);
        cursor.insertBlock();
        cursor.insertText(tr("Получил и выдал согласно ведомости приемщик молока______") + settings->getMilkInspector_2(),
                          textCharFormat);
        cursor.insertBlock();
        cursor.insertText(tr("Директор ") + settings->getFirmName(), textCharFormat);

    print.showDialog();
}
예제 #13
0
  void PrinterVisitor::visitGraphCellNodeBefore(GraphCell *node)
  {
    if( !ignore_ || firstChild_ )
    {

      ++currentTableRow_;
      table_->insertRows( currentTableRow_, 1 );

      // first column
      QTextTableCell tableCell( table_->cellAt( currentTableRow_, 0 ) );
      if( tableCell.isValid() )
      {
        if( !node->ChapterCounterHtml().isNull() )
        {
          QTextCursor cursor( tableCell.firstCursorPosition() );
          cursor.insertFragment( QTextDocumentFragment::fromHtml(
            node->ChapterCounterHtml() ));
        }
      }

      // second column
      tableCell = table_->cellAt( currentTableRow_, 1 );
      if( tableCell.isValid() )
      {
        QTextCursor cursor( tableCell.firstCursorPosition() );

        // input table
        QTextTableFormat tableFormatInput;
        tableFormatInput.setBorder( 0 );
        tableFormatInput.setColumns( 1 );
        tableFormatInput.setCellPadding( 2 );
        tableFormatInput.setBackground( QColor(245, 245, 255) ); // 200, 200, 255
        QVector<QTextLength> constraints;
        constraints << QTextLength(QTextLength::PercentageLength, 100);
                tableFormatInput.setColumnWidthConstraints(constraints);
        cursor.insertTable( 1, 1, tableFormatInput );

        QString html = node->textHtml();
        if( !node->isEvaluated() || node->isClosed() )
          html += "<br />";
        cursor.insertFragment( QTextDocumentFragment::fromHtml( html ));

        if( node->isEvaluated() && !node->isClosed() )
        {
          QTextTableFormat tableFormatOutput;
          tableFormatOutput.setBorder( 0 );
          tableFormatOutput.setColumns( 1 );
          tableFormatOutput.setCellPadding( 2 );
          QVector<QTextLength> constraints;
          constraints << QTextLength(QTextLength::PercentageLength, 100);
          tableFormatOutput.setColumnWidthConstraints(constraints);

          cursor = tableCell.lastCursorPosition();
          cursor.insertTable( 1, 1, tableFormatOutput );

          QString outputHtml( node->textOutputHtml() );

          outputHtml.remove( "file:///" );
          cursor.insertFragment( QTextDocumentFragment::fromHtml( outputHtml ));
        }

      }
      // print the plot
      if (node->mpPlotWindow && node->mpPlotWindow->isVisible()) {
        ++currentTableRow_;
        table_->insertRows( currentTableRow_, 1 );

        // first column
        tableCell = table_->cellAt( currentTableRow_, 1 );
        if( tableCell.isValid() )
        {
          QTextCursor cursor( tableCell.firstCursorPosition() );

          // input table
          QTextTableFormat tableFormatInput;
          tableFormatInput.setBorder( 0 );
          tableFormatInput.setColumns( 1 );
          tableFormatInput.setCellPadding( 2 );
          QVector<QTextLength> constraints;
          constraints << QTextLength(QTextLength::PercentageLength, 100);
                  tableFormatInput.setColumnWidthConstraints(constraints);
          cursor.insertTable( 1, 1, tableFormatInput );

          OMPlot::Plot *pPlot = node->mpPlotWindow->getPlot();
          // calculate height for widht while preserving aspect ratio.
          int width, height;
          if (pPlot->size().width() > 600) {
            width = 600;
            qreal ratio = (double)pPlot->size().height() / pPlot->size().width();
            height = width * qCeil(ratio);
          } else {
            width = pPlot->size().width();
            height = pPlot->size().height();
          }
          // create a pixmap and render the plot on it
          QPixmap plotPixmap(width, height);
          QwtPlotRenderer plotRenderer;
          plotRenderer.renderTo(pPlot, plotPixmap);
          // insert the pixmap to table
          cursor.insertImage(plotPixmap.toImage());
        }
      }

      if( firstChild_ )
        firstChild_ = false;
    }
  }