本文所用库的资源:
链接:https://pan.baidu.com/s/1-F1Gu-ENuFle8wE92h-h5Q
提取码:a7tz
1,本文库和代码需要在Qt5的32位编译器上运行,如下图所示,如需64位,博主有使用vs2022基于pdfium库的另一项目可供参考(链接)
2,此工程流程基本参考另一篇博客(链接),只是在其代码的基础上做了一些修改,定制化了自己的需求。
3,所以在此博主仅贴出自己的代码,如需具体流程请参考上述链接。
最终工程架构如下图:
pdfutils.h
#ifndef PDFUTILS_H
#define PDFUTILS_H
#include <QObject>
#include <QImage>
#include <QDir>
#include "poppler-qt5.h"
class PdfUtils
{
public:
explicit PdfUtils(QString filePath);
~PdfUtils();
// @pdf_path: xxx.pdf
void Pdf2Images();
//获取指定页pdf图像(页码从0开始)
QImage getPdfImage(int pageNumber);
private:
QString filePath;
int numPages;
void getPdfInfo();
};
#endif // PDFUTILS_H
pdfutils.cpp
#include "pdfutils.h"
PdfUtils::PdfUtils(QString filePath) {
this->filePath = filePath;
getPdfInfo();
}
PdfUtils::~PdfUtils() {
}
// @pdf_path: xxx.pdf
void PdfUtils::Pdf2Images() {
QString pdf_path = filePath;
pdf_path.chop(4);
QDir dir;
if (!dir.exists(pdf_path))
{
dir.mkdir(pdf_path);
}
for(int i = 0 ; i < numPages ; i++)
{
QImage my_img = getPdfImage(i);
my_img.save(pdf_path + "//" + pdf_path + "_" + QString::number(i, 10) + ".jpg");
}
}
QImage PdfUtils::getPdfImage(int pageNumber) {
QImage image;
Poppler::Document* document = Poppler::Document::load(filePath);
if (!document || document->isLocked()) {
// ... error message ....
delete document;
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(576, 576, -1, -1, -1, -1);
if (image.isNull()) {
// ... error message ...
return image;
}
// after the usage, the page must be deleted
delete pdfPage;
delete document;
return image;
}
void PdfUtils::getPdfInfo() {
numPages = 0;
Poppler::Document* document = Poppler::Document::load(filePath);
if (!document || document->isLocked()) {
// ... error message ....
delete document;
return;
}
numPages = document->numPages();
delete document;
}
main.cpp
#include "pdfutils.h"
#include <iostream>
int main(int argc, char *argv[])
{
QString my_pdf_path("test.pdf");
PdfUtils my_pdf(my_pdf_path);
my_pdf.Pdf2Images();
return 0;
}
最终运行效果为将pdf文件的所有页各生成一个图片,放在pdf文件的同名文件夹下,如下图所示: