How to print pdf file in Qt

限于喜欢 提交于 2019-12-19 03:13:36

问题


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; 
    } 
}

回答1:


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();
}


来源:https://stackoverflow.com/questions/8296021/how-to-print-pdf-file-in-qt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!