Unsolved How to generate .pdf files properly
-
Hello, I want to generate a .pdf file which should contain text, images and tables. I tried reading .html file and format .pdf based on it using QTextDocument class, but when .pdf is generated - not all styles are in the page. (padding, border-bottom etc). Some people are generating .pdf files using QPainter class, but I really don't think it is a right move. So which tool is the most suitable for generating .pdf files?
-
@Aronax
UseQWebEngine::printToPdf()
, orQPdfWriter
may be all you need. -
@JNBarchan I tried QWebEnginePage, but it prints empty .pdf page. My code:
QWebEnginePage page; page.setHtml(html); // QString html page.printToPdf(src, QPageLayout( QPageSize( QPageSize::A4 ), QPageLayout::Portrait, QMarginsF() ));
-
@Aronax
QWebEnginePage.setHtml()
(http://doc.qt.io/qt-5/qwebenginepage.html#setHtml) is, or may be, asynchronous. This means that you may be callingprintToPdf()
too early, before the HTML is fully there. I have (effectively ) put my call into slot forQWebEnginePage.loadFinished()
signal. You should try that.If still "empty", examine actual PDF generated or try on very simple small HTML first to verify whether it's anything about your actual content that is causing a problem.
P.S.
See also https://forum.qt.io/topic/83480/qt-5-9-1-does-qprinter-really-work-to-create-pdf-documents, and you may only need to useQPdfWriter
, I don't know. -
@JNBarchan Yeah. It works now, but i don't think that I should use QWebEnginePage just because I want to generate .pdf file is the optimal solution. QPdfWriter uses QPainter functions which is not good in my opinion..
-
@Aronax
I sort of agree with you, or did initially, but this seems to be how you do it in Qt. That's where the Qt PDF generator code is located, unless someone knows better that's all that's on offer. I'm not sure, but usingQPdfWriter
may be more lightweight, I wouldn't get hung up on the fact that it usesQPainter
, it's just producing PDF not actually drawing things.... -
@Aronax and what about Poppler PDF library? which has a companion wrapper Poppler Qt5 interface library.
As you will see there, the wrapper is used in KDE's document viewer Okular.
You even have this well detailed old article about displaying PDF files with Qt using Poppler.