WebEngine 小工具 Html2Pdf 示例

使用Qt WebEngine 将网页转换为 PDF 文档。

Html2Pdf演示了如何使用Qt WebEngine 实现将网页转换为 PDF 文档的命令行应用程序。

运行示例

要从 Qt Creator,打开Welcome 模式,然后从Examples 中选择示例。更多信息,请参阅Qt Creator: 教程:构建并运行

转换过程

为了将网页转换为 PDF 文档,我们需要

  1. 创建QWebEngineView
  2. 告诉QWebEngineView 开始加载目标 URL 并等待其完成。
  3. 告诉QWebEngineView 开始将加载的页面转换为 PDF 文件,并再次等待完成。
  4. 转换完成后,退出程序。

这个过程封装在Html2PdfConverter类中:

#include <QApplication>
#include <QCommandLineParser>
#include <QFile>
#include <QTextStream>
#include <QWebEngineView>

#include <functional>
#include <utility>

class Html2PdfConverter : public QObject
{
    Q_OBJECT
public:
    explicit Html2PdfConverter(QString inputPath, QString outputPath);
    int run();

private slots:
    void loadFinished(bool ok);
    void pdfPrintingFinished(const QString &filePath, bool success);

private:
    QString m_inputPath;
    QString m_outputPath;
    QScopedPointer<QWebEngineView> m_view;
};

在构造函数中,我们创建了QWebEngineView 并连接到QWebEngineView::loadFinishedQWebEngineView::pdfPrintingFinished 信号:

Html2PdfConverter::Html2PdfConverter(QString inputPath, QString outputPath)
    : m_inputPath(std::move(inputPath))
    , m_outputPath(std::move(outputPath))
    , m_view(new QWebEngineView)
{
    connect(m_view.data(), &QWebEngineView::loadFinished,
            this, &Html2PdfConverter::loadFinished);
    connect(m_view.data(), &QWebEngineView::pdfPrintingFinished,
            this, &Html2PdfConverter::pdfPrintingFinished);
}

run() 方法将通过要求QWebEnginePage 开始加载目标 URL 来触发转换过程。然后我们进入主事件循环:

int Html2PdfConverter::run()
{
    m_view->load(QUrl::fromUserInput(m_inputPath));
    return QApplication::exec();
}

加载完成后,我们开始生成 PDF。我们要求QWebEnginePage::printToPdf 方法将输出直接写入磁盘:

void Html2PdfConverter::loadFinished(bool ok)
{
    if (!ok) {
        QTextStream(stderr)
            << tr("failed to load URL '%1'").arg(m_inputPath) << "\n";
        QCoreApplication::exit(1);
        return;
    }

    m_view->printToPdf(m_outputPath);
}

一旦收到 PDF 转换完成的信号,剩下的工作就是报告潜在错误并退出程序:

void Html2PdfConverter::pdfPrintingFinished(const QString &filePath, bool success)
{
    if (!success) {
        QTextStream(stderr)
            << tr("failed to print to output file '%1'").arg(filePath) << "\n";
        QCoreApplication::exit(1);
    } else {
        QCoreApplication::quit();
    }
}

主函数

我们的main 函数负责设置QApplication 和解析命令行参数:

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QCoreApplication::setOrganizationName("QtExamples");
    QCoreApplication::setApplicationName("html2pdf");
    QCoreApplication::setApplicationVersion(QT_VERSION_STR);

    QCommandLineParser parser;
    parser.setApplicationDescription(
        QCoreApplication::translate("main", "Converts the web page INPUT into the PDF file OUTPUT."));
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addPositionalArgument(
        QCoreApplication::translate("main", "INPUT"),
        QCoreApplication::translate("main", "Input URL for PDF conversion."));
    parser.addPositionalArgument(
        QCoreApplication::translate("main", "OUTPUT"),
        QCoreApplication::translate("main", "Output file name for PDF conversion."));

    parser.process(QCoreApplication::arguments());

    const QStringList requiredArguments = parser.positionalArguments();
    if (requiredArguments.size() != 2)
        parser.showHelp(1);

    Html2PdfConverter converter(requiredArguments.at(0), requiredArguments.at(1));
    return converter.run();
}

请注意,要使用Qt WebEngine Widgets,我们需要创建QApplication ,而不是QCoreApplication ,尽管这是一个命令行应用程序。

示例项目 @ code.qt.io

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.