Как можно выполнить нумерацию страниц в нижнем колонтитуле при создании документа?

Рейтинг: 1Ответов: 0Опубликовано: 26.01.2023

Мне нужно, сделать отчет о работе устройства в формате .odt. Отчет будет содержать таблице в которых будут описаны этапы работы, тестирования и т.д. Отчет будит примерно на 10 страниц. Главная страница для редактирования, заполнить ФИО, и т.д. Таблицы, вставлять изображения, вставлять текс, научился. Но как добавлять нумерацию страниц в нижнем колонтитуле не знаю. Толи это делается как-то через курсор или в QTextEdit или прям QTextDocumentWriter. Вот простой код для понимания что делаю:

sourceTextEdit = new QTextEdit(); // создаем 
QString lorem=
      "Lorem ipsum tellus, eros ipsum lectus justo malesuada massa enim"
      " urna ipsum adipiscing in elementum porttitor arcu quisque "
      "curabitur justo sit eros orci. Rutrum, sit nec cursus et malesuada"
      " diam odio proin at tempus non."; // заполняем текстом
QTextCursor cursor = sourceTextEdit->textCursor(); // берем курсор
cursor.insertText(lorem); // вставляем текст
textDocument = sourceTextEdit->document();
QTextDocumentWriter writer; // записываем в документ
writer.setFormat("odf"); // задаем формат
writer.setFileName("report.odt"); // название документа
writer.write(textDocument); // пишем

Код просто выводит текс в документ report.odt. Вот хочу чтобы в документы в низу страницы в нижнем колонтитуле был указан номер страницы. В данном случаи должна быть указана '1'.

В дополнение к выше сказанному. Воспользовался ответом Sergey Tatarintsev. Написал вот такой код:

 #include <QPrinter>
 #include <QPainter>
 #include <QProgressDialog>
 #include <QApplication>
 #include <QTextDocument>
 #include <QTextTableCell>
 #include <QTextCursor>
 #include <QDebug>

static const int textMargins = 12; // in millimeters
static const int borderMargins = 10; // in millimeters

static double mmToPixels(QPrinter& printer, int mm)
{
    return mm * 0.039370147 * printer.resolution();
}

static void paintPage(QPrinter& printer, int pageNumber, int pageCount,
                      QPainter* painter, QTextDocument* doc,
                      const QRectF& textRect, qreal footerHeight)
{
    qDebug() << "Printing page" << pageNumber;
    const QSizeF pageSize = printer.paperRect().size();
    qDebug() << "pageSize=" << pageSize;

    const double bm = mmToPixels(printer, borderMargins);
    const QRectF borderRect(bm, bm, pageSize.width() - 2 * bm, pageSize.height() - 2 * bm);
    painter->drawRect(borderRect);

    painter->save();
    // textPageRect is the rectangle in the coordinate system of the QTextDocument, in pixels,
    // and starting at (0,0) for the first page. Second page is at y=doc->pageSize().height().
    const QRectF textPageRect(0, pageNumber * doc->pageSize().height(), doc->pageSize().width(), doc->pageSize().height());
    // Clip the drawing so that the text of the other pages doesn't appear in the margins
    painter->setClipRect(textRect);
    // Translate so that 0,0 is now the page corner
    painter->translate(0, -textPageRect.top());
    // Translate so that 0,0 is the text rect corner
    painter->translate(textRect.left(), textRect.top());
    doc->drawContents(painter);
    painter->restore();

    // Footer: page number or "end"
    QRectF footerRect = textRect;
    footerRect.setTop(textRect.bottom());
    footerRect.setHeight(footerHeight);
    qDebug() << "footerRect = " << footerRect;
    painter->drawText(footerRect, Qt::AlignVCenter | Qt::AlignRight, QObject::tr("Page %1/%2").arg(pageNumber+1).arg(pageCount));
}

static void printDocument(QPrinter& printer, QTextDocument* doc, QWidget* parentWidget)
{
    QPainter painter( &printer );
    QSizeF pageSize = printer.pageRect(QPrinter::DevicePixel).size(); // page size in pixels
    qDebug() << pageSize;
    // Calculate the rectangle where to lay out the text
    const double tm = mmToPixels(printer, textMargins);
    const qreal footerHeight = painter.fontMetrics().height(); // высота нижнего колонтитула
    qDebug() << "footerHeight = " << footerHeight;
    const QRectF textRect(tm, tm, pageSize.width() - 2 * tm, pageSize.height() - 2 * tm - footerHeight);
    qDebug() << "textRect=" << textRect;
    doc->setPageSize(textRect.size());

    const int pageCount = doc->pageCount();
    qDebug() << "pageCount = " << pageCount;

    QProgressDialog dialog( QObject::tr( "Printing" ), QObject::tr( "Cancel" ), 0, pageCount, parentWidget );
    dialog.setWindowModality( Qt::ApplicationModal );
    bool firstPage = true;
    for (int pageIndex = 0; pageIndex < pageCount; ++pageIndex)
    {
       dialog.setValue( pageIndex );
        if (dialog.wasCanceled())
             break;

        if (!firstPage)
            printer.newPage();

        paintPage( printer, pageIndex, pageCount, &painter, doc, textRect, footerHeight );
        firstPage = false;
    }
}

static void addTable(QTextCursor& cursor)
{
    const int columns = 4;
    const int rows = 1;

    QTextTableFormat tableFormat;
    tableFormat.setHeaderRowCount( 1 );
    QTextTable* textTable = cursor.insertTable( rows + 1,
                                                columns,
                                                tableFormat );
    QTextCharFormat tableHeaderFormat;
    tableHeaderFormat.setBackground( QColor( "#DADADA" ) );

    QStringList headers;
    headers << "Product" << "Reference" << "Price" << "Price with shipping";
    for( int column = 0; column < columns; column++ ) {
        QTextTableCell cell = textTable->cellAt( 0, column );
        Q_ASSERT( cell.isValid() );
        cell.setFormat( tableHeaderFormat );
        QTextCursor cellCursor = cell.firstCursorPosition();
        cellCursor.insertText( headers[column] );
    }
    int row = 0;
    for( int column = 0; column < columns; column++ ) {
        QTextTableCell cell = textTable->cellAt( row + 1, column );
        Q_ASSERT( cell.isValid() );
        QTextCursor cellCursor = cell.firstCursorPosition();
        const QString cellText = QString( "A 220.00" );
        cellCursor.insertText( cellText );
    }
    cursor.movePosition( QTextCursor::End );
}


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
    QTextDocument textDocument;
    QTextCursor cursor(&textDocument);
    cursor.insertText("This is the first page");
    addTable(cursor);
    QTextBlockFormat blockFormat;
    blockFormat.setPageBreakPolicy(QTextFormat::PageBreak_AlwaysBefore);
    cursor.insertBlock(blockFormat);
    cursor.insertText("This is the second page");
    QPrinter printer;
    printer.setPageSize(QPrinter::A4);
    printer.setOutputFileName("test.pdf");
    printer.setFullPage(true);
    printDocument(printer, &textDocument, 0);

    //создаем .odf файл
    QTextDocumentWriter writer;
    writer.setFormat("odf");
    writer.setFileName("report.odt");
    writer.write(&textDocument);*/
}

Нет в report.odt нумерации страниц.

Ответы

Ответов пока нет.