将 QWebView 打印为 PDF

Print a QWebView to PDF

我想将 QWebView 打印成 PDF 并保存在桌面上。 我实现了一个函数来执行此操作,代码如下:

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

现在我的问题是我的应用程序出现以下错误:

QPainter::begin(): Returned false

我可以确认这个错误是由上述函数引起的,另一方面,我在另一个项目中单独尝试了上面的代码以确认它有效——确实如此。

有什么建议吗?

只要存储 PDF 的位置没有拼写错误,上面的代码就可以完美运行——我的情况就是这样。

这样问题就解决了。