c++qtpdfqwebviewqprinter

Print a QWebView to PDF


I want to print an QWebView to PDF and save it on the desktop. I implemented a function to do so, and here's the code:

// Print to PDF
// Purpose: print incoming HTML source code to a PDF on the users desktop
// Input:   string containing the HTML source code, string with the desired filename of resulting PDF
// Output:  void
void MainWindow::printToPDF(QString htmlinput, QString filename)
{
    // Set location of resulting PDF
    QString saveLocation = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation) + "/" + filename + ".pdf";

    // Initialize printer and set save location
    QPrinter printer(QPrinter::HighResolution);
    printer.setOutputFileName(saveLocation);

    // Create webview and load html source
    QWebView webview;
    webview.setHtml(htmlinput);

    // Create PDF
    webview.print(&printer);
}

Now my problem is that I get the following error in my application:

QPainter::begin(): Returned false

I coud confirm that this error is caused by the above function, on the other hand I tried above code solely in another project to confirm it works – which it does.

Any suggestions?


Solution

  • The code above works perfectly- as long as the location to store the PDF does not have a typo -which it had in my case.

    So problem is solved.