QTextDocument cannot size or center images
-
[v5.15]
Hello,
I'm working on exporting a PDF document with data from various QML components. This includes some tables of data and two screenshot PNG images of
ChartView
s. The QML parent of these components sends the data to an export function in C++ looking roughly like the following:ExportManager::exportData(QUrl path, QStringList strings, QList<double> data, QVariant img1, QVariant img2)
However, I'm running into two problems when trying to insert this data into a PDF using
QTextDocument
andQPrinter
. The entire PDF is printed using pure HTML with CSS as follows:QTextDocument document; document.setHtml( html ); QPrinter printer( QPrinter::PrinterResolution ); printer.setOutputFormat( QPrinter::PdfFormat ); printer.setPageSize( QPageSize::Letter ); printer.setPageOrientation( landscape ? QPageLayout::Landscape : QPageLayout::Portrait ); printer.setOutputFileName( path.toLocalFile() ); printer.setPageMargins( QMarginsF(0, 0, 0, 0) ); document.print( &printer );
The image elements loaded into HTML with
<img src="/local/path/to/file.png">
ignore all width/height styling and centering. I've put various versions of the same HTML/CSS onto a website in Firefox/Chrome without any issue. I'm only using the supported attributes and styles listed in https://doc.qt.io/qt-5/richtext-html-subset.html, yet they're not working on<img>
elements.How can I even begin to debug this issue? Is there a better way to load images into the document than saving them and referencing paths in the HTML? All CSS is in the
<style>
header of the HTML, and is working for any other type of element. Is Qt applying its own CSS rules to images? IssetHtml
appropriate for this situation?I appreciate your help, thanks!
-
Hi,
From far old memories, what if you put your image between div tags and center the div ?
-
Yes, I've tried resizing and centering w/ a parent
<div>
, parent<table><tr><td align="center">
and many other ways... and it seems to respect any other non-<img> element. There's nodefaultStyleSheet
on the document and no other HTML/CSS beyond the two<img>
components.The images are added as resources like such (same QTextDocument as above):
document->addResource(QTextDocument::ImageResource, QUrl("derp://img1.png"), img1); document->addResource(QTextDocument::ImageResource, QUrl("derp://img2.png"), img2);
And then
setHtml
sets the following:<html> <body> <img width="50px" height="50px" src="derp://img1.png"/> <img width="50px" height="50px" src="derp://img2.png"/> </body>
I've started putting together a new document w/
QTextCursor
, but it'd be nice to just use HTML.