私はQtが初めてで、htmlページをPDFにエクスポートするプログラムを実行する必要があります
したがって、主なアイデアは、QWebPage
html を解釈し、それ自体を .pdf で pdf にエクスポートするために使用することQPrinter
です。
を使用するクラスとwebview
を使用するクラスが 2 つあります。QWebPage
Print
QPrinter
私はスロット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 はまだ実装されていないため、ソース コードを直接変更する必要があります)