Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

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);
        printer.setOutputFileName("/Users/jason/Desktop/example.pdf");
        printer.setOutputFormat(QPrinter::PdfFormat);
    
        QPainter painter;
        painter.begin(&printer);
        int width = painter.viewport().width();
        int height = painter.viewport().height();
        painter.setPen(Qt::black);
        painter.drawRect(0.25*width, 0.25*height, 0.5*width, 0.5*height);
        painter.end();
    }
    

    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;
    painter.begin(&pdfWriter);
    ...
    

  • 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