Printing pdf's is normally straightforward in Qt.

However there are issues under Mac PC's.

Take the code below.
It does work perfectly under Windows: clicking on the button creates a pdf file containing the small rectangle at the top left part of the page. The message "image printed on "print.pdf" " is displayed.

If I compile the same code under Mac and run the program from Qt creator, again I get a correct pdf.
But if I run the .app created by Qt, both "as is" and "fed up" using the macdeployqt utility, the painter does not construct and the message "Some error occurred" is displayed.

Any suggestions on how to overcome this?

Qt Code:
  1. #include "mainwindow.h"
  2. #include <QPainter>
  3. #include <QPaintEvent>
  4. #include <QPrinter>
  5. #include <QMessageBox>
  6.  
  7. MainWindow::MainWindow(QWidget *parent) :
  8. QMainWindow(parent)
  9. {
  10. btn = new QPushButton("doPdf", this);
  11. move(0,0);
  12. btn->adjustSize();
  13. btn->move(100,15);
  14. connect(btn,SIGNAL(clicked()),this,SLOT(btnClicked()));
  15. }
  16.  
  17. MainWindow::~MainWindow()
  18. {
  19. }
  20. void MainWindow::btnClicked(){
  21. bool ok;
  22. QRect r=QRect(10,10,80,50);
  23. QPrinter printer;
  24. QPainter painter;
  25. printer.setOutputFileName("print.pdf");
  26. ok=printer.isValid();
  27. ok=painter.begin(&printer);
  28. if(ok)
  29. painter.drawRect(r);
  30. ok=ok&&painter.end();
  31. if(ok)
  32. QMessageBox::information(this,"","image printed on \"print.pdf\"");
  33. else
  34. QMessageBox::information(this,"","Some error occurred!");
  35. }
  36. void MainWindow::paintEvent(QPaintEvent * ev){
  37. QRect r=QRect(10,10,80,50);
  38. QPainter painter(this);
  39. painter.drawRect(r);
  40. }
To copy to clipboard, switch view to plain text mode