25#include <QCoreApplication>
28#include <QJsonDocument>
33#include <QTemporaryDir>
34#include <QWebEnginePage>
36#include "moc_qgswebenginepage.cpp"
38using namespace Qt::StringLiterals;
42#include <QTemporaryFile>
50 , mPage { std::make_unique< QWebEnginePage >() }
67 mCachedSize = QSize();
71 bool finished =
false;
73 connect( mPage.get(), &QWebEnginePage::loadFinished, &loop, [&loop, &finished, &result](
bool ok ) {
78 mPage->setContent( data, mimeType, baseUrl );
81 loop.exec( QEventLoop::ExcludeUserInputEvents );
84 handlePostBlockingLoadOperations();
89 mPage->setContent( data, mimeType, baseUrl );
96 mCachedSize = QSize();
100 bool finished =
false;
102 connect( mPage.get(), &QWebEnginePage::loadFinished, &loop, [&loop, &finished, &result](
bool ok ) {
107 mPage->setHtml( html, baseUrl );
110 loop.exec( QEventLoop::ExcludeUserInputEvents );
113 handlePostBlockingLoadOperations();
119 mPage->setHtml( html, baseUrl );
126 mCachedSize = QSize();
130 bool finished =
false;
132 connect( mPage.get(), &QWebEnginePage::loadFinished, &loop, [&loop, &finished, &result](
bool ok ) {
137 mPage->setUrl( url );
140 loop.exec( QEventLoop::ExcludeUserInputEvents );
143 handlePostBlockingLoadOperations();
149 mPage->setUrl( url );
156 if ( mCachedSize.isValid() )
162 bool finished =
false;
163 mPage->runJavaScript(
"[document.documentElement.scrollWidth, document.documentElement.scrollHeight];", [&width, &height, &loop, &finished]( QVariant result ) {
164 width = result.toList().value( 0 ).toInt();
165 height = result.toList().value( 1 ).toInt();
171 loop.exec( QEventLoop::ExcludeUserInputEvents );
175 mCachedSize = QSize( width, height );
179void QgsWebEnginePage::handlePostBlockingLoadOperations()
186 bool finished =
false;
187 mPage->runJavaScript(
"[document.documentElement.scrollWidth, document.documentElement.scrollHeight];", [&width, &height, &loop, &finished]( QVariant result ) {
188 width = result.toList().value( 0 ).toInt();
189 height = result.toList().value( 1 ).toInt();
195 loop.exec( QEventLoop::ExcludeUserInputEvents );
198 mCachedSize = QSize( width, height );
208 static constexpr double dpi = 96.0;
209 const QSizeF pageSize = QSizeF( actualSize.width() / dpi, actualSize.height() / dpi );
212 bool finished =
false;
213 bool printOk =
false;
214 QString renderedPdfPath;
215 connect( mPage.get(), &QWebEnginePage::pdfPrintingFinished, &loop, [&loop, &finished, &printOk, &renderedPdfPath](
const QString &pdfPath,
bool success ) {
217 renderedPdfPath = pdfPath;
229 const QPageLayout layout = QPageLayout( QPageSize( pageSize, QPageSize::Inch ), QPageLayout::Portrait, QMarginsF( 0, 0, 0, 0 ), QPageLayout::Inch, QMarginsF( 0, 0, 0, 0 ) );
230 mPage->printToPdf( f.fileName(), layout );
234 loop.exec( QEventLoop::ExcludeUserInputEvents );
239 QgsPdfRenderer renderer( renderedPdfPath );
240 renderer.render( painter, painterRect, 0 );
248 throw QgsNotSupportedException( QObject::tr(
"Rendering web pages requires a QGIS build with PDF4Qt library support" ) );
252QString QgsWebEnginePage::htmlToPdfExecutable()
254 QString executable = QProcessEnvironment::systemEnvironment().value( u
"QGIS_HTML_TO_PDF_EXECUTABLE"_s );
255 if ( executable.isEmpty() )
257#if defined( Q_OS_WIN )
266QString QgsWebEnginePage::htmlToPdfReturnCodeToString(
int code )
276 return tr(
"Loading HTML failed" );
281 return tr(
"Executing Javascript initialization code failed" );
286 return tr(
"Printing HTML to PDF failed" );
291 return tr(
"Loading settings JSON failed" );
296 return tr(
"Unknown error" );
304 const QString executable = htmlToPdfExecutable();
305 if ( executable.isEmpty() || !QFile::exists( executable ) )
307 errorMessage = tr(
"qgis_html_to_pdf utility not found" );
311 const QTemporaryDir tempDir;
313 QStringList allArgs = args;
316 const QString settingsFilename = tempDir.filePath( u
"settings.json"_s );
317 allArgs.append( u
"--settings=%1"_s.arg( settingsFilename ) );
319 QJsonObject settingsObj = QJsonObject::fromVariantMap( settings.
asMap() );
320 QJsonDocument jsonDocument( settingsObj );
321 QFile settingsFile( settingsFilename );
322 if ( !settingsFile.open( QFile::WriteOnly | QFile::Truncate ) )
324 errorMessage = tr(
"writing settings to temporary file failed" );
328 settingsFile.write( jsonDocument.toJson() );
329 settingsFile.close();
332 QgsBlockingProcess process( executable, allArgs );
333 process.setStdErrHandler( [](
const QByteArray &ba ) {
QgsDebugError( ba ); } );
334 process.setStdOutHandler( [](
const QByteArray &ba ) {
QgsDebugMsgLevel( ba, 2 ); } );
335 const int returnCode = process.run( feedback );
336 errorMessage = htmlToPdfReturnCodeToString( returnCode );
337 return returnCode == 0;
342 const QString executable = htmlToPdfExecutable();
343 if ( executable.isEmpty() || !QFile::exists( executable ) )
345 errorMessage = tr(
"qgis_html_to_pdf utility not found" );
349 const QTemporaryDir tempDir;
350 const QString outputFilename = tempDir.filePath( u
"content.html"_s );
351 QFile outputFile( outputFilename );
352 if ( !outputFile.open( QFile::WriteOnly | QFile::Truncate ) )
354 errorMessage = tr(
"writing HTML to temporary file failed" );
358 outputFile.write( html.toUtf8() );
361 const QStringList args { outputFilename, pdfFileName, u
"--width=%1"_s.arg( width ) };
362 return doPrintToPdf( args, settings, errorMessage, feedback );
367 const QString executable = htmlToPdfExecutable();
368 if ( executable.isEmpty() || !QFile::exists( executable ) )
370 errorMessage = tr(
"qgis_html_to_pdf utility not found" );
374 const QStringList args { url.toString(), pdfFileName, u
"--width=%1"_s.arg( width ) };
375 return doPrintToPdf( args, settings, errorMessage, feedback );
379 const QString &html, QPainter *painter,
const QRectF &painterRect, QString &errorMessage, QSizeF &renderedSize,
const QgsHtmlRenderSettings &settings,
QgsFeedback *feedback
383 const QTemporaryDir tempDir;
384 const QString renderedPdfPath = tempDir.filePath( u
"content.pdf"_s );
386 const double dpi = ( painter && painter->device() ) ? painter->device()->logicalDpiX() : 96.0;
387 const int cssWidth = std::max( 1,
static_cast< int >( std::round( painterRect.width() * 96.0 / dpi ) ) );
389 if ( !
printToPdfBlocking( html, renderedPdfPath, errorMessage, cssWidth, settings, feedback ) )
395 return renderBlockingInternal( painter, renderer, errorMessage, painterRect, renderedSize );
399 ( void ) painterRect;
400 ( void ) errorMessage;
403 ( void ) renderedSize;
404 throw QgsNotSupportedException( QObject::tr(
"Rendering HTML requires a QGIS build with PDF4Qt library support" ) );
411 const QTemporaryDir tempDir;
412 const QString renderedPdfPath = tempDir.filePath( u
"content.pdf"_s );
414 const double dpi = ( painter && painter->device() ) ? painter->device()->logicalDpiX() : 96.0;
415 const int cssWidth = std::max( 1,
static_cast< int >( std::round( painterRect.width() * 96.0 / dpi ) ) );
417 if ( !
printToPdfBlocking( url, renderedPdfPath, errorMessage, cssWidth, settings, feedback ) )
423 return renderBlockingInternal( painter, renderer, errorMessage, painterRect, renderedSize );
427 ( void ) painterRect;
428 ( void ) errorMessage;
430 ( void ) renderedSize;
432 throw QgsNotSupportedException( QObject::tr(
"Rendering HTML requires a QGIS build with PDF4Qt library support" ) );
437bool QgsWebEnginePage::renderBlockingInternal( QPainter *painter,
QgsPdfRenderer &renderer, QString &errorMessage,
const QRectF &painterRect, QSizeF &renderedSize )
441 errorMessage = tr(
"Generated PDF contains no pages" );
446 if ( mediaBox.isEmpty() || mediaBox.width() <= 0 )
450 const double aspectRatio = mediaBox.height() / mediaBox.width();
451 const double targetHeight = painterRect.width() * aspectRatio;
453 const QRectF targetRect( painterRect.left(), painterRect.top(), painterRect.width(), targetHeight );
454 renderedSize = targetRect.size();
455 return renderer.
render( painter, targetRect, 0 );
static QString libexecPath()
Returns the path with utility executables (help viewer, crssync, ...).
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Encapsulates settings for rendering HTML content.
bool isEmpty() const
Returns true no settings are set.
QVariantMap asMap() const
Returns the settings encapsulated in a variantmap, for passing to the qgis_html_to_pdf utility.
Custom exception class which is raised when an operation is not supported.
Utility class for rendering PDF documents.
QRectF pageMediaBox(int pageNumber) const
Returns the media box for the specified page.
int pageCount() const
Returns the number of pages in the PDF.
bool render(QPainter *painter, const QRectF &painterRect, int pageIndex)
Renders the PDF from the specified path to a painter.
bool setContent(const QByteArray &data, const QString &mimeType=QString(), const QUrl &baseUrl=QUrl(), bool blocking=false)
Sets the content of the web page to data.
static bool renderBlocking(const QString &html, QPainter *painter, const QRectF &painterRect, QString &errorMessage, QSizeF &renderedSize, const QgsHtmlRenderSettings &settings=QgsHtmlRenderSettings(), QgsFeedback *feedback=nullptr)
Renders HTML content to a painter asynchronously.
void loadStarted()
This signal is emitted when the page starts loading content.
bool setHtml(const QString &html, const QUrl &baseUrl=QUrl(), bool blocking=false)
Sets the content of this page to html.
bool setUrl(const QUrl &url, bool blocking=false)
Sets the url of the web page to be displayed.
void loadFinished(bool ok)
This signal is emitted when the page finishes loading content.
QgsWebEnginePage(QObject *parent=nullptr)
Constructor for QgsWebEnginePage, with the specified parent widget.
bool render(QPainter *painter, const QRectF &painterRect)
Renders the web page contents to a painter.
void loadProgress(int progress)
This signal is emitted when the global progress status changes.
~QgsWebEnginePage() override
QWebEnginePage * page()
Returns a reference to the QWebEnginePage.
QSize documentSize() const
Returns the size of the page document, in pixels.
static bool printToPdfBlocking(const QString &html, const QString &pdfFileName, QString &errorMessage, int width, const QgsHtmlRenderSettings &settings=QgsHtmlRenderSettings(), QgsFeedback *feedback=nullptr)
Renders HTML content to a PDF file asynchronously.
#define BUILTIN_UNREACHABLE
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)