How to print a text file on a printer in Qt?

I wrote some sample data in a text file. I want to print this text file on my printer. Can someone please tell me how the code will be for this using Qt4?

+5
source share
1 answer

To print text to a printer, you need QPrinter and QPainter.

The following code prints a sample text to a printer selected from the dialog box (QPrintDialog).

#include <QApplication>
#include <QPrinter>
#include <QPrintDialog>
#include <QPainter>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QString text =
            "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do\n"
            "eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut\n"
            "enim ad minim veniam, quis nostrud exercitation ullamco laboris\n"
            "nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\n"
            "in reprehenderit in voluptate velit esse cillum dolore eu fugiat\n"
            "nulla pariatur. Excepteur sint occaecat cupidatat non proident,\n"
            "sunt in culpa qui officia deserunt mollit anim id est laborum.\n";

    QPrinter printer;

    QPrintDialog *dialog = new QPrintDialog(&printer);
    dialog->setWindowTitle("Print Document");

    if (dialog->exec() != QDialog::Accepted)
        return -1;

    QPainter painter;
    painter.begin(&printer);

    painter.drawText(100, 100, 500, 500, Qt::AlignLeft|Qt::AlignTop, text);

    painter.end();

    return 0;
}

To print the contents of your text file, you need to parse the file line by line to create a QString with the content. The generated QString can be printed as example text in the example.

QPrinter QPainter

+10

All Articles