QPrinter + QPainter writes invalid PDF file

325 Views Asked by At

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?

1

There are 1 best solutions below

0
Jason Smith On

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 my printer!

Using painter.setPen(QPen(QBrush(Qt::red), 100.0)) shows a clear rectangle as expected.