Qt World Summit: Submit your Presentation

QPrinter + QPainter writes invalid PDF file

  • I am simply trying to draw a rectangle to a PDF file using QPrinter + QPainter:

    #include <QtWidgets>
    #include <QPrinter>
    int main(int argc, char *argv[]) {
        QApplication a(argc, argv);
        QPrinter printer(QPrinter::HighResolution);
        QPainter painter;
        int width = painter.viewport().width();
        int height = painter.viewport().height();
        painter.drawRect(0.25*width, 0.25*height, 0.5*width, 0.5*height);

    Using MacOS 10.15.4 and Qt 5.15.2 this results in a blank/invalid PDF file. The same code without the QPrinter.setOutputFormat and QPrinter.setOutputFileName correctly prints a rectangle on paper.

    How can I using QPrinter/QPdfWriter + QPainter to draw to a PDF file?

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    For QPdfWriter, just use QPainter on it directly.

  • @SGaist Thanks, but I get the same invalid/blank PDF when using

    QPdfWriter pdfWriter("/Users/jason/Desktop/example.pdf");
    QPainter painter;

  • Lifetime Qt Champion

    In what way is it invalid ?

  • I am a fool. I thought the PDF was blank, but it turns out if I zoom in really really far, I can see a faint grey line. Apparently the resolution of a PDF is much higher than that of a printer!

    Using painter.setPen(QPen(QBrush(Qt::red), 100.0)); shows a clear rectangle as expected both using QPrinter and QPdfWriter.

Log in to reply