WebEngine ウィジェット Html2Pdf の例

Qt WebEngine を使ってウェブページをPDF文書に変換します。

Html2Pdfは、Qt WebEngine を使用して、ウェブページを PDF ドキュメントに変換するコマンドラインアプリケーションを実装する方法を示します。

例の実行

からサンプルを実行するには Qt Creatorからサンプルを実行するには、Welcome モードを開き、Examples からサンプルを選択します。詳細については、「例の構築と実行」を参照してください。

変換プロセス

ウェブページを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 ウィジェットを使用するには、QCoreApplication ではなくQApplication を作成する必要があることに注意してください。

プロジェクト例 @ 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.