QT5.15.2加载pdf为QGraphicsScene的背景

5.15.2使用pdf

必须要安装QT源码,可以看到编译器lib目录已经有pdf相关的lib文件,d是debug

1.找到源码目录:D:\soft\QT\5.15.2\Src\qtwebengine\include

复制这两个文件夹到编译器的包含目录中:D:\soft\QT\5.15.2\msvc2019_64\include

2.找到D:\soft\QT\5.15.2\Src\qtwebengine\src\pdf\api目录,将目录下的文件夹全部复制替换到D:\soft\QT\5.15.2\msvc2019_64\include\QtPdf中。

3.将D:\soft\QT\5.15.2\Src\qtwebengine\src\pdfwidgets以下文件复制替换到到D:\soft\QT\5.15.2\msvc2019_64\include\QtPdfWidgets中

4.修改pro文件,不用加入附加包含目录,只需要加入附加库目录和lib名称即可

cpp 复制代码
LIBS += -LD:/soft/Qt/5.15.2/msvc2019_64/lib

CONFIG(debug, debug|release){
    LIBS += -lQt5Pdfd
    LIBS += -lQt5PdfWidgetsd
}
else
{
    LIBS += -lQt5Pdf
    LIBS += -lQt5PdfWidgets
}

5.测试

cpp 复制代码
#include <QApplication>
#include <QtPdf/QPdfDocument>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QPdfDocument *doc = new QPdfDocument;
    doc->load("D:/1.pdf");
    QSizeF pageSize = doc->pageSize(0);
    QImage image = doc->render(0,pageSize.toSize());
    image.save("D:/1.png");
    return a.exec();
}

加载pdf为QGraphicsScene的背景

cpp 复制代码
#include <QApplication>
#include <QtPdf/QPdfDocument>
#include <QGraphicsScene>
#include <QGraphicsView>
class MyQGraphicsScene:public QGraphicsScene
{
public:
    MyQGraphicsScene(QObject *parent = nullptr):QGraphicsScene(parent)
    {
        doc = new QPdfDocument(this);
    }
    void drawBackground(QPainter *painter, const QRectF &rect) override
    {
        doc->load("D:/1.pdf");
        QSizeF pageSize = doc->pageSize(0);
        QImage image = doc->render(0,pageSize.toSize());
        painter->setPen(Qt::blue);
        painter->setBrush(image);
        painter->drawRect(sceneRect());
    }

private:
    QPdfDocument *doc = nullptr;
};

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

    // 创建自定义场景
    MyQGraphicsScene *scene = new MyQGraphicsScene();
    scene->setSceneRect(0,0,500,400);
    // 创建视图,并设置场景
    QGraphicsView *view = new QGraphicsView(scene);
    view->setFixedSize(800,600);
    view->show();
    return a.exec();
}

重写QGraphicsScene的drawBackground方法即可达到目的

相关推荐
Quz11 小时前
QML Hello World 入门示例
qt
xcyxiner3 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner4 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner4 天前
DicomViewer (添加模型类)3
qt
xcyxiner5 天前
DicomViewer (目录调整) 2
qt
xcyxiner5 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
桥田智能7 天前
桥田智能 QT-650S:面向白车身焊装的 800kg 重载快换解决方案
开发语言·qt·系统架构
weixin_397574097 天前
PDF复杂表格的1:1还原引擎:跨页表格自动拼接技术实战
大数据·人工智能·pdf
Metaphor6927 天前
使用 Python 将 PDF 转换为 HTML
python·pdf·html
2601_961845157 天前
粉笔行测5000题电子版|pdf|解析
pdf·新媒体运营·github·个人开发·内容运营·规格说明书·极限编程