Qt笔记-利用QAxObject将文件夹内的所有docx转pdf

x33g5p2x  于2022-08-17 转载在 其他  
字(1.9k)|赞(0)|评价(0)|浏览(711)

这里用Qt提供的AXContainer库就可以了,但这个只能在Windows平台上用。

首先要先了解几个知识点:

ExportAsFixedFormat是将文件导出为指定格式:这里关键的有2个参数:

FileName: 文件名;

FileType:为17代表是pdf

整体代码如下:

DocxToPdfDemo.pro

QT += axcontainer gui widgets

CONFIG += c++11 console
CONFIG -= app_bundle

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
        main.cpp

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

main.cpp

#include <QAxObject>
#include <QAxWidget>
#include <QDebug>
#include <QApplication>
#include <QFile>
#include <QDir>

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

    QDir dir("D:\\数学");
    if(!dir.exists()){

        qDebug() << "dir error";
        return 0;
    }

    dir.setFilter(QDir::Files | QDir::NoSymLinks);
    QFileInfoList list = dir.entryInfoList();
    for(int i = 0; i < list.size(); i++){

        QFileInfo fileInfo = list.at(i);
        QString fileName = fileInfo.fileName();
        QString filePath = fileInfo.absoluteFilePath();
        QString dirName = dir.path();

        QAxWidget word("Word.Application");
        word.setProperty("Visible", false);
        QAxObject * documents = word.querySubObject("Documents");
        QAxObject * document = documents->querySubObject("Open(QString)", filePath);

        QVariant OutputFileName(dirName + "/" + fileName.mid(0, fileName.lastIndexOf(".")) + ".pdf");
        QVariant ExportFormat(17);
        QVariant OpenAfterExport(false);

        document->querySubObject("ExportAsFixedFormat(const QVariant&,const QVariant&,const QVariant&)",
                                 OutputFileName,
                                 ExportFormat,
                                 OpenAfterExport);

        document->dynamicCall("Close(boolean)",false);
        word.dynamicCall("Quit (void)");

        qDebug() << filePath + " to pdf success";
    }

    return a.exec();
}

程序运行截图如下:

源码打包下载地址:

Qt/DocxToPdfDemo at master · fengfanchen/Qt · GitHub

相关文章