Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print text file to printer in Qt? [closed]

Tags:

file

printing

qt

I have written some sample data onto a text file. I want to print this text file to my printer. Could anyone please tell me how the code will be in order to do this using Qt4?

like image 993
Roonyunlimited Avatar asked Jul 09 '12 14:07

Roonyunlimited


1 Answers

You will need to use a QPrinter and a QPainter object to print text to the printer.

The following code will print a sample text to a printer selected from a 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;
}

In order to print the content of your text file, you will need to parse the file line by line to generate a QString with the content. The generated QString can be printed like the sample text in the example.

For more information read the docs for QPrinter and QPainter

like image 183
bluetiger9 Avatar answered Nov 01 '22 18:11

bluetiger9