Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print pdf file in Qt

Tags:

c++

printing

pdf

qt

I have tried to write some code to print a pdf file using Qt but somehow it's not working. If anybody has any idea to solve this problem, please provide your tips.

void ChartViewer::onprintBtnClicked(){ 
    String filename = QFileDialog::getOpenFileName(this,"Open File",QString(),"Pdf File(*.pdf)"); 
    qDebug()<<"Print file name is "<<filename; 
    if(!filename.isEmpty()) { 
        if(QFileInfo(filename).suffix().isEmpty()) 
            filename.append(".pdf"); 

        QPrinter printer(QPrinter::HighResolution);         
        printer.setOutputFormat(QPrinter::PdfFormat);  
        printer.setOutputFileName(filename);
        QPrintDialog*dlg = new QPrintDialog(&printer,this); 

        if(textedit->textCursor().hasSelection()) 
            dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection); 

        dlg->setWindowTitle(tr("Print Document")); 

        if(dlg->exec() == QDialog::Accepted) { 
            textedit->print(&printer); 
        } 

        delete dlg; 
    } 
}
like image 902
lekhraj Avatar asked Nov 28 '11 12:11

lekhraj


1 Answers

I didn't understand your question, but now I get it. You want to print PDF file using Qt, you don't want to print into PDF, right?

Qt does not have support for loading and display PDF. For PDF support in Qt you need external library poppler. Check this article.

Poppler allows you to render PDF files into QImage and you can easily print QImage like this.

Here is how do you print text into PDF file.

I tried to edit your code so that I can test it a bit and it works for me, can you check? Maybe try to check if QPrinter::isValid() returns true in your environment.

#include <QtGui>
#include <QtCore>

int main(int argc, char **argv) {
    QApplication app(argc, argv);
    QTextEdit parent;
    parent.setText("We are the world!");
    parent.show();

    QString filename = QFileDialog::getOpenFileName(&parent,"Open File",QString(),"Pdf File(*.pdf)"); 
    qDebug()<<"Print file name is "<<filename; 
    if(!filename.isEmpty()) {
        if(QFileInfo(filename).suffix().isEmpty()) {
            filename.append(".pdf"); 
        }

        QPrinter printer(QPrinter::HighResolution);         
        printer.setOutputFormat(QPrinter::PdfFormat);  
        printer.setOutputFileName(filename);
        QPrintDialog*dlg = new QPrintDialog(&printer,&parent); 
        dlg->setWindowTitle(QObject::tr("Print Document")); 

        if(dlg->exec() == QDialog::Accepted) { 
            parent.print(&printer); 
        } 
        delete dlg; 
    } 
    return app.exec();
}
like image 165
LukasT Avatar answered Oct 05 '22 23:10

LukasT