Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QWebEnginePage::printToPdf creates empy page



  • My Html2Pdf program:

    int main(int argc, char *argv[])
    {
        QApplication app(argc, argv);
    
        // arguments
        QString inputPath = argv[1];
        QString outputPath = argv[2];
    
        // read input file
        QFile inputFile(inputPath);
        inputFile.open(QIODevice::ReadOnly | QIODevice::Text);
        QTextStream in(&inputFile);
        QString html = in.readAll();
    
        // get input file directory
        QFileInfo inputFileInfo(inputFile);
        QDir inputFileDir = inputFileInfo.dir();
    
        // prepare page
        QWebEnginePage page;
        QObject::connect(&page, &QWebEnginePage::pdfPrintingFinished, []{exit(0);});
        page.setHtml(html, inputFileDir.path());
    
        //print page
        page.printToPdf(outputPath);
    
        return app.exec();
    }
    

    And it doesn't work. It produces pdf file containing one empy page. What do I do wrong?


  • Lifetime Qt Champion

    @Tarae My guess is: you need to wait until the HTML page is loaded.
    https://doc.qt.io/qt-5/qwebenginepage.html#loadFinished



  • @Tarae
    I know from experience that what @jsulm says is indeed the case! QWebEnginePage loads asynchronously, if you set off a page print before that's completed you get how the page is now --- which is empty :)



  • @jsulm @JonB Thank you! This works:

    QWebEnginePage page;
    Object::connect(&page, &QWebEnginePage::pdfPrintingFinished, []{exit(0);});
    QObject::connect(&page, &QWebEnginePage::loadFinished, [&page, &outputPath](bool ok){if (ok) page.printToPdf(outputPath);});
    page.setHtml(html, inputFileDir.path());
    

Log in to reply