웹엔진 위젯 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.