Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 633
appfrosch Avatar asked Dec 19 '25 12:12

appfrosch


1 Answers

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.

like image 160
appfrosch Avatar answered Dec 21 '25 04:12

appfrosch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!