morteza ali ahmadi
morteza ali ahmadi

Reputation: 455

Qt QProcess sometimes works and sometimes does not work

I want to convert a ps file to pdf by ps2pdf and this codes in Qt:

QPixmap graphPng(filePath +  "report/pictures/graph-000.png");
int graphPsWidth=graphPng.width();
int graphPsHeight=graphPng.height();

//convert "ps" file to "pdf" file
QProcess process;
QStringList arg;
arg<<"-dDEVICEWIDTHPOINTS=" + QString::number(graphPsWidth)<<"-dDEVICEHEIGHTPOINTS=" + QString::number(graphPsHeight)<<"export/report/pictures/graph-000.ps"<<"export/report/pictures/graph-000.pdf";
process.start("ps2pdf",arg);
//process.waitForStarted(-1);
process.waitForFinished(-1);

(I use a png file as the same dimensions of the ps file to get the dimensions and use it in creating pdf file)

I don't know why sometimes the pdf file is created and some times without any output message (process::readAllStandardError() and process::readAllStandardOutput()) there is no pdf file!

When the pdf file is not created if I run that immediately in terminal, the pdf file will be created!!!

What is the reason and how can I solve it?

Upvotes: 1

Views: 717

Answers (2)

morteza ali ahmadi
morteza ali ahmadi

Reputation: 455

I can solve the problem by handling the RAM, because if the ram exceed the specific limit (almost near the full capacity of the RAM), the QProcess can not be started. So every time it diagnoses the exceeded limit, the PDF file is not created and vice versa.

Upvotes: 0

eyllanesc
eyllanesc

Reputation: 244291

It is always advisable to verify all the steps, so I share a more robust version of your code.

For example it is not necessary to use QPixmap, the correct thing is to use QImage. In addition, the path of the files is verified.

#include <QCoreApplication>
#include <QDir>
#include <QProcess>
#include <QImage>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QDir directory(QString("%1%2%3")
                   .arg(a.applicationDirPath())
                   .arg(QDir::separator())
                   .arg("export/report/pictures/"));

    QString name = "graph-000";
    QString png_path = directory.filePath(name + ".png");
    QString ps_path = directory.filePath(name + ".ps");

    // verify path
    Q_ASSERT(QFileInfo(png_path).exists());
    Q_ASSERT(QFileInfo(ps_path).exists());

    QString pdf_path = directory.filePath(name+".pdf");

    QImage img(png_path);
    int graphPsWidth = img.width();
    int graphPsHeight = img.height();

    QProcess process;
    QStringList arg;
    arg << QString("-dDEVICEWIDTHPOINTS=%1").arg(graphPsWidth) <<
         QString("-dDEVICEHEIGHTPOINTS=%1").arg(graphPsHeight) <<
         ps_path << pdf_path;

    process.start("ps2pdf",arg);
    process.waitForFinished();
    Q_ASSERT(QFileInfo(pdf_path).exists());
    return 0;
}

Upvotes: 1

Related Questions