简体   繁体   中英

How to print image file from a printer using QT

I am trying to print an image file on printer using QWebview but instead of image blank page is printed. Please find the below code.

void ChartViewer::onprintBtnClicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,"Open File",QString(),"Pdf File(*.png)");
    qDebug()<<"Print file name is "<<fileName;
    if(fileName.endsWith(".png"))
    {
        QPrinter printer;
        QWebView *view = new QWebView;
        QPrintDialog *dlg = new QPrintDialog(&printer,this);
        printer.setOutputFileName(fileName);
        if(dlg->exec() != QDialog::Accepted)
            return;
        view->load(fileName);
        view->print(&printer);
    }
}

If I use view->show() then it has shown the image properly but printed page is coming blank. Request you to please look into the above code and correct me where I am doing wrong.

Regards, Lekhraj

You load some png file into fileName. Then you set QPrinter to print to that png file with printer.setOutputFileName(fileName); .I suppose it is wrong, it should be some different pdf file probably.

I'm not sure if I understand what are you trying to do? How to print image file using QPrinter? Into pdf file? Why are trying to use QWebView? You can use QImage to load image file and then paint with QPainter on QPrinter.

#include <QtGui>
#include <QtCore>

int main(int argc, char** argv) {
        QApplication app(argc, argv);

        QString fileName = QFileDialog::getOpenFileName(0,"Open File",QString(),"PNG File(*.png)");

        QPrinter printer;
        QPrintDialog *dlg = new QPrintDialog(&printer,0);
        if(dlg->exec() == QDialog::Accepted) {
                QImage img(fileName);
                QPainter painter(&printer);
                painter.drawImage(QPoint(0,0),img);
                painter.end();
        }

        delete dlg;

        QTimer::singleShot(1, &app, SLOT(quit()));
        app.exec();
        return 0;
}

Some of your issues may overlap with your other question https://stackoverflow.com/questions/8297239/how-to-print-pdf-file-in-qt

You try to print the QWebView immediately after you call its load() function. But the QWebView has not yet loaded the content and the view is therefore blank. You need to connect the QWebView's loadFinished signal to some slot where you can call the print() function. Read the QWebView's documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM