0

私はQtが初めてで、htmlページをPDFにエクスポートするプログラムを実行する必要があります

したがって、主なアイデアは、QWebPagehtml を解釈し、それ自体を .pdf で pdf にエクスポートするために使用することQPrinterです。

を使用するクラスとwebviewを使用するクラスが 2 つあります。QWebPagePrintQPrinter

私はスロットmain.cppに接続LoadFinishedしています:PrintPDF

Print *pdf = new Print(args);
webview *nav = new webview();
nav->setPrinter(pdf->getPrinter());

if(nav->load(args) == false) {
    qDebug() << "can't load page";
    return 0;
}
//when the page page is ready, we will print it
QObject::connect(nav->getFrame(), SIGNAL(loadFinished(bool)), nav, SLOT(printPDF(bool)));

webview.cppのクラス:

#include "webview.h"
webview::webview()
{
    page = new QWebPage;
    printer = 0;
}

webview::~webview()
{
    delete page;
}

bool webview::load(Arguments *args)
{
    QRegularExpression url("^(file|http)://");
    QRegularExpression fullPath("^/");

    QRegularExpressionMatch pathMatch = fullPath.match(args->getSource());
    QRegularExpressionMatch urlMatch = url.match(args->getSource());

    // see http://qt-project.org/doc/qt-4.8/qwebsettings.html#WebAttribute-enum for more informations
    page->settings()->setAttribute(QWebSettings::LocalStorageEnabled, true);
    page->settings()->setAttribute(QWebSettings::AutoLoadImages, true);
    page->settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
    page->settings()->setAttribute(QWebSettings::PrintElementBackgrounds, true);
    page->settings()->setAttribute(QWebSettings::PluginsEnabled, true);

    if(pathMatch.hasMatch()) {
        page->mainFrame()->load(QUrl::fromLocalFile(args->getSource()));
    } else {
        if (urlMatch.hasMatch()) {
            page->mainFrame()->load(QUrl(args->getSource()));
        } else {
            fprintf(stderr, "%s\n", qPrintable(QApplication::translate("main", "Error: Invalide source file")));
            return false;
        }
    }
    return true;
}

void webview::printPDF(bool ok)
{
    if(ok == true) {
        qDebug() << "okay";
    } else
        qDebug() << "non okay";
    if(printer != 0)
        page->mainFrame()->print(printer);
}

これは私のコンソールの表示です:

問題ありませ
ん QPainter::begin: ペイント デバイスは、一度に 1 人のペインターによってのみペイントできます。

エラーの原因がどこにあるのかわかりません。プロジェクト全体はこちら

引数は次のとおりです。

./htmltopdf http://stackoverflow.com destinationFolder

(destinationFolder はまだ実装されていないため、ソース コードを直接変更する必要があります)

4

2 に答える 2

0

問題は別のところにありました:

main.cppはこれを持っていました:

QObject::connect(nav->getFrame(), SIGNAL(loadFinished(bool)), nav, SLOT(printPDF(bool)));
[...]
delete args;
delete pdf;
delete nav;

return app.exec();

app.exec()Qtイベントを処理する一種の無限ループであり、プログラムが閉じないようにします。この関数を呼び出す前に削除を続行すると、新しく割り当て解除されたポインターが使用されます。

私が行った場合 :

bool result = app.exec();

delete args;
delete pdf;
delete nav;

return result;

正常に動作しています。

于 2014-08-05T12:38:26.637 に答える