winodws下使用qt 调用poppler库,实现pdf文件加载,显示的功能。
INCLUDEPATH += $$PWD/include/poppler DEPENDPATH += $$PWD/include/poppler win32: LIBS += -L$$PWD/lib/poppler/ -lpoppler -lpoppler-qt5头文件
class PdfUtils { public: explicit PdfUtils(); ~PdfUtils(); //打开pdf文件 bool OpenPdf(QString filePath); //是否已经打开文件 bool isOpen(); //获取当前文件路径 QString getFilePath(); //获取pdf总页码 int getNumPages(); //获取pdf页面大小 QSize getPageSize(); //获取指定页pdf图像(页码从0开始) QImage getPdfImage(int pageNumber); //渲染pdf页面到qwidget bool loadPage2Widget(int pageNumber); //关闭pdf文件 bool ClosePdf(); private: Poppler::Document* document; bool opened = false; int numPages; QSize pageSize; QString filePath; }; #endif // PDFUTILS_Hcpp文件
#include "pdfutils.h" #include <QDebug> #include <QPaintEngine> #include <QPixmap> #include <QThread> PdfUtils::PdfUtils(){ } PdfUtils::~PdfUtils(){ } bool PdfUtils::OpenPdf(QString filePath) { this->filePath = filePath; document = Poppler::Document::load(filePath); if (!document || document->isLocked()) { // ... error message .... delete document; this->opened = false; return this->opened; } //设置文字抗锯齿 document->setRenderHint(Poppler::Document::TextAntialiasing); numPages = document->numPages(); Poppler::Page* pdfPage = document->page(0); if(pdfPage != 0){ pageSize = pdfPage->pageSize(); } this->opened = true; return this->opened; } bool PdfUtils::isOpen() { return this->opened; } QString PdfUtils::getFilePath() { return this->filePath; } int PdfUtils::getNumPages() { return numPages; } QSize PdfUtils::getPageSize() { return pageSize; } bool PdfUtils::ClosePdf() { if(this->opened){ delete document; } this->opened = false; this->numPages = 0; return true; } QImage PdfUtils::getPdfImage(int pageNumber){ QImage image; if(!isOpen()){ return image; } // Document starts at page 0 Poppler::Page* pdfPage = document->page(pageNumber); if (pdfPage == 0) { // ... error message ... return image; } // Generate a QImage of the rendered page image = pdfPage->renderToImage(200, 200, -1, -1, -1, -1); if (image.isNull()) { // ... error message ... return image; } // after the usage, the page must be deleted delete pdfPage; return image; }使用方法:
bool isSuccess = pdfUtils.OpenPdf("./temp.pdf"); QImage pdfImage = pdfUtils.getPdfImage(0);