PDA

View Full Version : Painter not active when exporting to pdf with different filename



estanisgeyer
21st March 2012, 04:58
I need to export multiple reports to pdf, but when I use the function QPrinter::setOutputFileName the error occurs:
QPainter::begin(): Returned false
QPainter::translate: Painter not active
QPainter::setPen: Painter not active
QPainter::setRenderHint: Painter must be active to set rendering hints

See the code:



for (int i = 0; model->rowCount() > i; i++)
{
int x = model->data(model->index(i, 0), Qt::DisplayRole).toInt();

QString filename = dir.append(QDir::separator()).append(model->data(model->index(i, 1), Qt::DisplayRole).toString()).append(".pdf");

QPrinter * printer = new QPrinter(QPrinter::HighResolution);
printer->setOutputFormat(QPrinter::PdfFormat);
printer->setOrientation(QPrinter::Portrait);
printer->setPaperSize(QSizeF(210, 297), QPrinter::Millimeter);
printer->setFullPage(true);
printer->setOutputFileName(filename);

QPrintPreviewWidget * printPreview = new QPrintPreviewWidget(printer, this);

Report * r = new Report(x, this); // Report generation class
connect(printPreview, SIGNAL(paintRequested(QPrinter*)), r, SLOT(Print(QPrinter*)));

printPreview->print();
disconnect(printPreview, SIGNAL(paintRequested(QPrinter*)), r, SLOT(Print(QPrinter*)));
}


If you remove the function "printer->setOutputFileName, will work, but will send directly to the printer. How can I solve this?

Thanks,

Marcelo E. Geyer

ChrisW67
21st March 2012, 05:58
Well, you could start by making sure that file name is what you think it is, contains no illegal characters for a file name, and that the file can be written in the location specified.

Also these points are worth thinking about:

You need not be using QDir::separator() for the reasons described in the documentation.
The QPrinter need not be allocated on the heap; it only makes a memory leak at the moment.
The QPrintPreviewWidget is totally unnecessary: just call the Print() function directly.
IMHO "QSizeF(210, 297), QPrinter::Millimeter" is more obvious when expressed as QPrinter::A4.