linux 下使用poppler qt5

poppler qt5是poppler的扩展模块,使用qt图形库的开发者对于开发pdf插件来说,这个开源库无疑是非常方便的。本篇介绍如何使用这个库,并且配置开发环境。

1.在poppler官网下载源码,解压到本地目录后切换到这个根目录,打开命令行:

  • $./configure

  • $make

  • $sudo make install

2.编译安装完后,我们用命令行查一下包,并且安装对应的开发库:

  • $apt-cache search poppler-qt5

  • $sudo apt-get install libpoppler-qt5-dev
    3.安装完了我们就可以子qt中使用这个库了,如果不确定有没这个包,可以通过一下命令检查一下:

  • $pkg-config --cflags poppler-qt5

4.在qt 的工程文件中添加一下配置

这时候就能使用poppler qt5的库了,它提供了很方便的接口。写一个例子获取pdf文件的第一张截图:

QPixmap FilePreviewIconProvider::getPlainTextPreviewIcon(QString fileUrl){
    QFile file(fileUrl);
    if(!file.exists())
        return QPixmap(QSize(PIXMAP_WIDTH,PIXMAP_HEIGHT));

    if(!file.open(QIODevice::ReadOnly))
        return QPixmap(QSize(PIXMAP_WIDTH,PIXMAP_HEIGHT));

    file.waitForBytesWritten(200);
    QString text = file.readAll();
    file.close();

    QStringList strs = text.split("\n");

    QImage img(QSize(PIXMAP_WIDTH,PIXMAP_HEIGHT),QImage::Format_ARGB32);
    QPainter painter(&img);
    QFont font;
    font.setPixelSize(12);
    painter.setFont(font);
    QPen pen;
    pen.setColor(QColor(0,0,0));
    painter.setPen(pen);

    int counter = 0;
    for(auto line : strs){
        QString str;
        QStringList subStrs;
        for(int i = 0;iisLocked())){
        delete document;
        qDebug()<<"file reading error....";
        return QPixmap(QSize(PIXMAP_WIDTH,PIXMAP_HEIGHT));
    }
    qDebug()<<"pdf document read successfully!";

    if(document == 0){
        qDebug()<<"pdf page is null";
        return QPixmap(QSize(PIXMAP_WIDTH,PIXMAP_HEIGHT));
    }

    Poppler::Page* pdfPage = document->page(0); //Document start at page 0

    QImage img = pdfPage->renderToImage(72,72,0,0,pdfPage->pageSize().width(),pdfPage->pageSize().height());
    if(img.isNull()){
        qDebug()<<"render error";
        return QPixmap(QSize(PIXMAP_WIDTH,PIXMAP_HEIGHT));
    }

    img = img.scaled(QSize(PIXMAP_WIDTH,PIXMAP_HEIGHT),Qt::KeepAspectRatio,Qt::SmoothTransformation);
    delete pdfPage;
    return QPixmap::fromImage(img);

}

你可能感兴趣的:(qt5)