QGIS API Documentation 4.3.0-Master (0cef2469b72)
Loading...
Searching...
No Matches
qgswebenginepage.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgswebenginepage.h
3 -------------------
4 begin : December 2023
5 copyright : (C) 2023 by Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
18#include "qgsconfig.h"
19#include "qgswebenginepage.h"
20
21#include "qgsapplication.h"
22#include "qgslogger.h"
23#include "qgsrunprocess.h"
24
25#include <QCoreApplication>
26#include <QDir>
27#include <QEventLoop>
28#include <QJsonDocument>
29#include <QJsonObject>
30#include <QPainter>
31#include <QSizeF>
32#include <QString>
33#include <QTemporaryDir>
34#include <QWebEnginePage>
35
36#include "moc_qgswebenginepage.cpp"
37
38using namespace Qt::StringLiterals;
39
40#ifdef HAVE_PDF4QT
41#include "qgspdfrenderer.h"
42#include <QTemporaryFile>
43#else
44#include "qgsexception.h"
45#endif
46
47
49 : QObject( parent )
50 , mPage { std::make_unique< QWebEnginePage >() }
51{
52 // proxy some signals from the page
53 connect( mPage.get(), &QWebEnginePage::loadStarted, this, &QgsWebEnginePage::loadStarted );
54 connect( mPage.get(), &QWebEnginePage::loadProgress, this, &QgsWebEnginePage::loadProgress );
55 connect( mPage.get(), &QWebEnginePage::loadFinished, this, &QgsWebEnginePage::loadFinished );
56}
57
59
60QWebEnginePage *QgsWebEnginePage::page()
61{
62 return mPage.get();
63}
64
65bool QgsWebEnginePage::setContent( const QByteArray &data, const QString &mimeType, const QUrl &baseUrl, bool blocking )
66{
67 mCachedSize = QSize();
68 if ( blocking )
69 {
70 QEventLoop loop;
71 bool finished = false;
72 bool result = true;
73 connect( mPage.get(), &QWebEnginePage::loadFinished, &loop, [&loop, &finished, &result]( bool ok ) {
74 finished = true;
75 result = ok;
76 loop.exit();
77 } );
78 mPage->setContent( data, mimeType, baseUrl );
79 if ( !finished )
80 {
81 loop.exec( QEventLoop::ExcludeUserInputEvents );
82 }
83 if ( result )
84 handlePostBlockingLoadOperations();
85 return result;
86 }
87 else
88 {
89 mPage->setContent( data, mimeType, baseUrl );
90 return true;
91 }
92}
93
94bool QgsWebEnginePage::setHtml( const QString &html, const QUrl &baseUrl, bool blocking )
95{
96 mCachedSize = QSize();
97 if ( blocking )
98 {
99 QEventLoop loop;
100 bool finished = false;
101 bool result = true;
102 connect( mPage.get(), &QWebEnginePage::loadFinished, &loop, [&loop, &finished, &result]( bool ok ) {
103 finished = true;
104 result = ok;
105 loop.exit();
106 } );
107 mPage->setHtml( html, baseUrl );
108 if ( !finished )
109 {
110 loop.exec( QEventLoop::ExcludeUserInputEvents );
111 }
112 if ( result )
113 handlePostBlockingLoadOperations();
114
115 return result;
116 }
117 else
118 {
119 mPage->setHtml( html, baseUrl );
120 return true;
121 }
122}
123
124bool QgsWebEnginePage::setUrl( const QUrl &url, bool blocking )
125{
126 mCachedSize = QSize();
127 if ( blocking )
128 {
129 QEventLoop loop;
130 bool finished = false;
131 bool result = true;
132 connect( mPage.get(), &QWebEnginePage::loadFinished, &loop, [&loop, &finished, &result]( bool ok ) {
133 finished = true;
134 result = ok;
135 loop.exit();
136 } );
137 mPage->setUrl( url );
138 if ( !finished )
139 {
140 loop.exec( QEventLoop::ExcludeUserInputEvents );
141 }
142 if ( result )
143 handlePostBlockingLoadOperations();
144
145 return result;
146 }
147 else
148 {
149 mPage->setUrl( url );
150 return true;
151 }
152}
153
155{
156 if ( mCachedSize.isValid() )
157 return mCachedSize;
158
159 QEventLoop loop;
160 int width = -1;
161 int height = -1;
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();
166 finished = true;
167 loop.exit();
168 } );
169 if ( !finished )
170 {
171 loop.exec( QEventLoop::ExcludeUserInputEvents );
172 }
173
174
175 mCachedSize = QSize( width, height );
176 return mCachedSize;
177}
178
179void QgsWebEnginePage::handlePostBlockingLoadOperations()
180{
181 // Following a blocking content load, do some other quick calculations which involve local event loops.
182 // This allows callers to avoid having to make another later call to a method which would other involve a local event loop.
183 QEventLoop loop;
184 int width = 0;
185 int height = 0;
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();
190 finished = true;
191 loop.exit();
192 } );
193 if ( !finished )
194 {
195 loop.exec( QEventLoop::ExcludeUserInputEvents );
196 }
197
198 mCachedSize = QSize( width, height );
199}
200
201
202#ifdef HAVE_PDF4QT
203bool QgsWebEnginePage::render( QPainter *painter, const QRectF &painterRect )
204{
205 const QSize actualSize = documentSize();
206
207 // TODO -- is this ALWAYS 96?
208 static constexpr double dpi = 96.0;
209 const QSizeF pageSize = QSizeF( actualSize.width() / dpi, actualSize.height() / dpi );
210
211 QEventLoop loop;
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 ) {
216 finished = true;
217 renderedPdfPath = pdfPath;
218 printOk = success;
219 loop.exit();
220 } );
221
222 // generate file name for temporary intermediate PDF file
223 QTemporaryFile f;
224 if ( !f.open() )
225 return false;
226
227 f.close();
228
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 );
231
232 if ( !finished )
233 {
234 loop.exec( QEventLoop::ExcludeUserInputEvents );
235 }
236
237 if ( printOk )
238 {
239 QgsPdfRenderer renderer( renderedPdfPath );
240 renderer.render( painter, painterRect, 0 );
241 }
242 return printOk;
243}
244
245#else
246bool QgsWebEnginePage::render( QPainter *, const QRectF & )
247{
248 throw QgsNotSupportedException( QObject::tr( "Rendering web pages requires a QGIS build with PDF4Qt library support" ) );
249}
250#endif
251
252QString QgsWebEnginePage::htmlToPdfExecutable()
253{
254 QString executable = QProcessEnvironment::systemEnvironment().value( u"QGIS_HTML_TO_PDF_EXECUTABLE"_s );
255 if ( executable.isEmpty() )
256 {
257#if defined( Q_OS_WIN )
258 executable = QgsApplication::libexecPath() + "qgis_html_to_pdf.exe";
259#else
260 executable = QgsApplication::libexecPath() + "qgis_html_to_pdf";
261#endif
262 }
263 return executable;
264}
265
266QString QgsWebEnginePage::htmlToPdfReturnCodeToString( int code )
267{
268 // matches values in QgsHtmlToPdf::ResultCode
269 switch ( code )
270 {
271 case 0:
272 return QString();
273
274 case 1:
275 {
276 return tr( "Loading HTML failed" );
277 }
278
279 case 2:
280 {
281 return tr( "Executing Javascript initialization code failed" );
282 }
283
284 case 3:
285 {
286 return tr( "Printing HTML to PDF failed" );
287 }
288
289 case 4:
290 {
291 return tr( "Loading settings JSON failed" );
292 }
293
294 default:
295 {
296 return tr( "Unknown error" );
297 }
298 }
300}
301
302bool QgsWebEnginePage::doPrintToPdf( const QStringList &args, const QgsHtmlRenderSettings &settings, QString &errorMessage, QgsFeedback *feedback )
303{
304 const QString executable = htmlToPdfExecutable();
305 if ( executable.isEmpty() || !QFile::exists( executable ) )
306 {
307 errorMessage = tr( "qgis_html_to_pdf utility not found" );
308 return false;
309 }
310
311 const QTemporaryDir tempDir;
312
313 QStringList allArgs = args;
314 if ( !settings.isEmpty() )
315 {
316 const QString settingsFilename = tempDir.filePath( u"settings.json"_s );
317 allArgs.append( u"--settings=%1"_s.arg( settingsFilename ) );
318
319 QJsonObject settingsObj = QJsonObject::fromVariantMap( settings.asMap() );
320 QJsonDocument jsonDocument( settingsObj );
321 QFile settingsFile( settingsFilename );
322 if ( !settingsFile.open( QFile::WriteOnly | QFile::Truncate ) )
323 {
324 errorMessage = tr( "writing settings to temporary file failed" );
325 return false;
326 }
327
328 settingsFile.write( jsonDocument.toJson() );
329 settingsFile.close();
330 }
331
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;
338}
339
340bool QgsWebEnginePage::printToPdfBlocking( const QString &html, const QString &pdfFileName, QString &errorMessage, int width, const QgsHtmlRenderSettings &settings, QgsFeedback *feedback )
341{
342 const QString executable = htmlToPdfExecutable();
343 if ( executable.isEmpty() || !QFile::exists( executable ) )
344 {
345 errorMessage = tr( "qgis_html_to_pdf utility not found" );
346 return false;
347 }
348
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 ) )
353 {
354 errorMessage = tr( "writing HTML to temporary file failed" );
355 return false;
356 }
357
358 outputFile.write( html.toUtf8() );
359 outputFile.close();
360
361 const QStringList args { outputFilename, pdfFileName, u"--width=%1"_s.arg( width ) };
362 return doPrintToPdf( args, settings, errorMessage, feedback );
363}
364
365bool QgsWebEnginePage::printToPdfBlocking( const QUrl &url, const QString &pdfFileName, QString &errorMessage, int width, const QgsHtmlRenderSettings &settings, QgsFeedback *feedback )
366{
367 const QString executable = htmlToPdfExecutable();
368 if ( executable.isEmpty() || !QFile::exists( executable ) )
369 {
370 errorMessage = tr( "qgis_html_to_pdf utility not found" );
371 return false;
372 }
373
374 const QStringList args { url.toString(), pdfFileName, u"--width=%1"_s.arg( width ) };
375 return doPrintToPdf( args, settings, errorMessage, feedback );
376}
377
379 const QString &html, QPainter *painter, const QRectF &painterRect, QString &errorMessage, QSizeF &renderedSize, const QgsHtmlRenderSettings &settings, QgsFeedback *feedback
380)
381{
382#ifdef HAVE_PDF4QT
383 const QTemporaryDir tempDir;
384 const QString renderedPdfPath = tempDir.filePath( u"content.pdf"_s );
385
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 ) ) );
388
389 if ( !printToPdfBlocking( html, renderedPdfPath, errorMessage, cssWidth, settings, feedback ) )
390 {
391 return false;
392 }
393
394 QgsPdfRenderer renderer( renderedPdfPath );
395 return renderBlockingInternal( painter, renderer, errorMessage, painterRect, renderedSize );
396#else
397 ( void ) html;
398 ( void ) painter;
399 ( void ) painterRect;
400 ( void ) errorMessage;
401 ( void ) settings;
402 ( void ) feedback;
403 ( void ) renderedSize;
404 throw QgsNotSupportedException( QObject::tr( "Rendering HTML requires a QGIS build with PDF4Qt library support" ) );
405#endif
406}
407
408bool QgsWebEnginePage::renderBlocking( const QUrl &url, QPainter *painter, const QRectF &painterRect, QString &errorMessage, QSizeF &renderedSize, const QgsHtmlRenderSettings &settings, QgsFeedback *feedback )
409{
410#ifdef HAVE_PDF4QT
411 const QTemporaryDir tempDir;
412 const QString renderedPdfPath = tempDir.filePath( u"content.pdf"_s );
413
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 ) ) );
416
417 if ( !printToPdfBlocking( url, renderedPdfPath, errorMessage, cssWidth, settings, feedback ) )
418 {
419 return false;
420 }
421
422 QgsPdfRenderer renderer( renderedPdfPath );
423 return renderBlockingInternal( painter, renderer, errorMessage, painterRect, renderedSize );
424#else
425 ( void ) url;
426 ( void ) painter;
427 ( void ) painterRect;
428 ( void ) errorMessage;
429 ( void ) feedback;
430 ( void ) renderedSize;
431 ( void ) settings;
432 throw QgsNotSupportedException( QObject::tr( "Rendering HTML requires a QGIS build with PDF4Qt library support" ) );
433#endif
434}
435
436#ifdef HAVE_PDF4QT
437bool QgsWebEnginePage::renderBlockingInternal( QPainter *painter, QgsPdfRenderer &renderer, QString &errorMessage, const QRectF &painterRect, QSizeF &renderedSize )
438{
439 if ( renderer.pageCount() < 1 )
440 {
441 errorMessage = tr( "Generated PDF contains no pages" );
442 return false;
443 }
444
445 const QRectF mediaBox = renderer.pageMediaBox( 0 );
446 if ( mediaBox.isEmpty() || mediaBox.width() <= 0 )
447 return false;
448
449 // Calculate target height preserving the content's natural aspect ratio
450 const double aspectRatio = mediaBox.height() / mediaBox.width();
451 const double targetHeight = painterRect.width() * aspectRatio;
452
453 const QRectF targetRect( painterRect.left(), painterRect.top(), painterRect.width(), targetHeight );
454 renderedSize = targetRect.size();
455 return renderer.render( painter, targetRect, 0 );
456}
457#endif
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.
Definition qgsfeedback.h:44
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
Definition qgis.h:8483
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:80
#define QgsDebugError(str)
Definition qgslogger.h:71