How to print pdf file in Qt

前端 未结 1 1398
北海茫月
北海茫月 2021-01-05 20:20

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.

相关标签:
1条回答
  • 2021-01-05 21:13

    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();
    }
    
    0 讨论(0)
提交回复
热议问题