Browse PDFs in a Qt Widgets application
Some months ago Shawn Rutledge blogged about the new QtPdf module, a Qt wrapper around the PDFium library, which allows you to render PDF documents to QImages. Since that blog post we have invested some more work into the module to make it more useful in your day-to-day projects.
One long-standing bug report against Qt is QTBUG-28886, which is about adding a widget to Qt that can easily render a PDF document. That does not only involve rendering of single pages, but also to provide ways to navigate through the document, so say hello to…
QPdfView is a widget that renders a PDF document that has been loaded through QPdfDocument. It offers a single page and a continuous multi page mode and the user can choose between fit-to-width, fit-in-view or a custom zoom level.
To avoid the UI getting blocked while the PDF document is rendered, the rendering of the single pages is off-loaded to a worker thread.
Getting the code
To test the new features, just clone the QtPdf repository, install it and compile the examples like this:
git clone git://code.qt.io/qt-labs/qtpdf cd qtpdf git submodule update --init --recursive qmake make cd examples/pdf/pdfviewer qmake make ./pdfviewer
Using QPdfView is quite simple – loading a PDF document and showing it on screen can be done in a couple of lines now:
#include <QPdfDocument> #include <QPdfView> QPdfDocument *document = new QPdfDocument; document->load("document.pdf"); QPdfView *view = new QPdfView; view->setDocument(document); view->show();
If you want to see a more extensive example, have a look at the examples/pdf/pdfviewer directory in the QtPdf module.
At the moment the PDFium version which is shipped with QtPdf is rather outdated, and therefore does not include the latest security fixes from upstream. The blocking factor from upgrading it is PDFium’s build system, which has changed from gyp to gn; the build system integration inside QtPdf hasn’t followed up yet.
Thankfully, Michal Klocek from The Qt Company provided the first patches that allow us to implement a proper integration between qmake and gn, so that compiling the QtPdf module with an up-to-date PDFium version should be much easier in the future.
On the UI side there are many things to do as well, here just a short selection from the top of my head:
- extend navigation possibilities (e.g. follow links, navigate to sections)
- add custom QtQuick item to render PDF pages (patches in progress already)
- extend and improve documentation.
Nonetheless, I hope this module will be useful to the many users who are looking for an easy solution to render PDF documents in their Qt applications!
Populating a Combobox from Qt Designer
Using Clang-Format to Ensure Style Guidelines
Un-sorting headers in QTableView
KDAB believes that it is critical for our business to contribute to the Qt framework and C++ thinking, to keep pushing these technologies forward to ensure they remain competitive.