How to print image file from printer using QT

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

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 displayed the image correctly, but the printed page is empty. Ask you to read the code above and fix me where I am doing wrong.

Regards, Lekhraj

+1
qt
Nov 29 '11 at 12:28
source share
2 answers

You upload some png file to fileName. Then you set QPrinter to print in this png file using printer.setOutputFileName(fileName); . I suppose this is wrong, probably it should be some other PDF file.

I'm not sure if I understand what you are trying to do? How to print image file using QPrinter? To pdf file? Why are you trying to use QWebView? You can use QImage to load an image file, and then draw a QPainter on a 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 problems may coincide with your other question .

+6
Nov 29 '11 at 13:06
source share
— -

You are trying to print a QWebView immediately after calling the load () function. But QWebView has not loaded the content yet, and therefore the view is empty. You need to connect the QWebView loadFinished signal to some slot where you can call the print () function. Read the QWebView documentation .

+1
Nov 29 '11 at 16:23
source share



All Articles