Qt QProcess有时有效,有时不起作用



我想通过ps2pdfps文件转换为pdf,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);

(我使用png文件作为ps文件的相同尺寸来获取尺寸并将其用于创建pdf文件(

我不知道为什么有时会创建pdf文件,有时没有任何输出消息(process::readAllStandardError()process::readAllStandardOutput()(没有pdf文件!

如果我立即在终端中运行pdf文件,则未创建该文件时,将创建pdf文件!!

原因是什么,我该如何解决?

始终建议验证所有步骤,因此我分享了您的代码的更健壮版本。

例如不必使用QPixmap,正确的做法是使用QImage。此外,还会验证文件的路径。

#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;
}

我可以通过处理 RAM 来解决问题,因为如果 ram 超过特定限制(几乎接近 RAM 的全部容量(,则无法启动QProcess。因此,每次诊断超出限制时,都不会创建PDF文件,反之亦然。

相关内容

最新更新