Search code examples
qtqpainterqpixmapqprinter

How to print multiple tables into one pdf


I'm trying to print multiple table (qtablewidget) objects in single pdf using qt.

I can print one table, using the code provided in(https://forum.qt.io/topic/80501/qpainter-howto-draw-table/7)

QPixmap pix(widget->size());
QPainter painter(&pix);
widget->render(&painter);
painter.end();
QPrinter printer(QPrinter::HighResolution);
printer.setOrientation(QPrinter::Landscape);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setPaperSize(QPrinter::A4);
printer.setOutputFileName("test.pdf"); // will be in build folder

painter.begin(&printer);
painter.drawPixmap(0, 0, pix);
painter.end();

However, if I try to print multiple tables, the code fails. If I create multiple QPainters, qt just outputs multiple pdfs, with one table in each pdf. I'm trying to do it using one QPainter and multiple QPixmaps, but no success so far.

Would anyone please let me know how I can get around it?

Any help would be appreciated

Regards,


Solution

  • How does the code fail? The below should work (I didn't test it). Note the absence of manual object lifetime management: let the compiler do it for you. A QPainter is a proper C++ class and knows how to release its resources without having to manually invoke QPainter::end().

    void printWidgets(QWidgetList widgets) {
      QVector<QPixmap> pixmaps;
      for (auto *w : widgets) {
        QPixmap pix(w->size());
        QPainter painter(pix);
        w->render(&painter);
        pixmaps.push_back(pix);
      }
    
      QPrinter printer(QPrinter::HighResolution);
      printer.setOrientation(QPrinter::Landscape);
      printer.setOutputFormat(QPrinter::PdfFormat);
      printer.setPaperSize(QPrinter::A4);
      printer.setOutputFileName("test.pdf"); // will be in build folder
    
      QPainter painter(&printer);
      QPoint pos;    
      for (auto &pix : qAsConst(pixmaps)) {
        painter.drawPixmap(pos, pix);
        pos.ry() += pix.height(); // stack the output vertically
      }
    }