Qt 将PDF文件转高清图片源码分享

📅 2026/7/12 20:12:12
Qt 将PDF文件转高清图片源码分享
Qt 将pdf转高清图片源码分享一、源码分享1、效果展示2、源码分享二、pdf模块详解1、 模块概述与引入1.1 、模块组成1.2、 在项目中启用2、核心类详解2.1 、QPdfDocument2.2、 QPdfDocumentRenderOptions2.3 、渲染流程与图像处理3、高级应用与注意事项4、 核心类与API表格QPdfDocumentQPdfDocumentRenderOptionsQPdfBookmarkModelQPdfLinkModel5. 总结一、源码分享1、效果展示2、源码分享#includeQScreen#includeQPdfDocument#includeQPdfDocumentRenderOptions#includeQImage#includeQFile#includeQDir#includeQGuiApplication#includeQPainter#includemainwindow.h#includeui_mainwindow.hMainWindow::MainWindow(QWidget*parent):QMainWindow(parent),ui(newUi::MainWindow){ui-setupUi(this);}MainWindow::~MainWindow(){deleteui;}boolMainWindow::pdfToHighResImage(constQStringpdfPath,constQStringimgPath,QSize size,intdpi){QPdfDocument doc;autoerrdoc.load(pdfPath);if(err!QPdfDocument::Error::None){qDebug()load pdf error code:err;returnfalse;}// 校验自定义尺寸if(!size.isValid()||size.width()0||size.height()0){qDebug()input size width or height less zero!;doc.close();returnfalse;}// 拆分路径自动创建目录QFileInfoimageFileInfo(imgPath);// 获取后缀并判断格式QString suffiximageFileInfo.suffix().toLower();QString imgFormat;intquality-1;if(suffixpng){imgFormatPNG;}elseif(suffixjpg||suffixjpeg){imgFormatJPG;quality100;// jpg最高画质防模糊}else{qDebug()unsupported image extensions, only png / jpg / jpeg are supported!;doc.close();returnfalse;}// 只转换第0页如需指定页码可再加pageIndex参数intpageIdx0;qDebug()doc.pagePointSize(pageIdx);QPdfDocumentRenderOptions opts;opts.setRenderFlags(QPdfDocumentRenderOptions::RenderFlag::None);QImage imgdoc.render(pageIdx,size,opts);if(img.isNull()){qDebug()page pageIdx1 rendering failed!;doc.close();returnfalse;}QImagewhiteBgImg(size,QImage::Format_RGB32);// RGB无透明通道whiteBgImg.fill(Qt::white);// 铺满纯白色背景QPainterpainter(whiteBgImg);painter.setRenderHints(QPainter::Antialiasing|QPainter::TextAntialiasing);painter.drawImage(0,0,img);// 将带透明的PDF图绘制到白底上painter.end();// 替换原img后续保存用白底图imgstd::move(whiteBgImg);intdotsPerMeterqRound(dpi/25.4*1000);img.setDotsPerMeterX(dotsPerMeter);img.setDotsPerMeterY(dotsPerMeter);if(imgFormatPNG){// PNG额外写入文本信息看图软件可识别img.setText(DPI,QString::number(dpi));}boolsaveOk;if(quality0)saveOkimg.save(imgPath,imgFormat.toUtf8().data(),quality);elsesaveOkimg.save(imgPath,imgFormat.toUtf8().data());if(!saveOk)qDebug()failed to save the image:imgPath;elseqDebug()success to save the image:imgPath;doc.close();returnsaveOk;}voidMainWindow::on_pushButton_clicked(){pdfToHighResImage(L000137362.pdf,L000137362.jpg,QSize(896,1534),300);pdfToHighResImage(L000137362.pdf,L000137362.png,QSize(896,1534),300);}在pro中添加pdf模块。二、pdf模块详解Qt6 引入了功能强大的Qt PDF模块为开发者提供了原生、跨平台的 PDF 文档处理能力无需依赖第三方库。该模块基于 Qt 的图形架构能够高效地渲染、查看和打印 PDF 文件。1、 模块概述与引入1.1 、模块组成Qt PDF模块主要包含以下核心类QPdfDocument: 用于加载、解析和获取 PDF 文档的元数据如页数、作者、标题及页面内容。它是操作 PDF 的入口。QPdfSelection: 处理文档中的文本选择。QPdfLink: 表示文档内的链接如目录跳转、URL。QPdfBookmarkModel: 提供文档书签大纲的模型便于集成到树形视图。QPdfPageNavigator: 辅助进行页面导航。此外该模块还提供了与 Qt Widgets 和 Qt Quick 集成的便捷类QQuickPdfDocument和QQuickPdfPage(Qt Quick)QPdfView(Qt Widgets): 一个功能完整的 PDF 查看器控件。1.2、 在项目中启用在 Qt 项目文件 (.pro) 中添加以下配置来引入 PDF 模块QT pdf对于 CMake 项目则在CMakeLists.txt中链接对应的库find_package(Qt6 REQUIRED COMPONENTS Pdf) target_link_libraries(your_target PRIVATE Qt6::Pdf)2、核心类详解2.1 、QPdfDocument这是最核心的类负责管理 PDF 文档的生命周期。关键方法load(const QString fileName)/load(QIODevice *device): 从文件或设备加载 PDF。status(): 返回加载状态 (QPdfDocument::Status)。pageCount(): 获取文档总页数。pagePointSize(int pageIndex): 获取指定页面的尺寸以点为单位1点1/72英寸。render(int pageIndex, QSize imageSize, QPdfDocumentRenderOptions options QPdfDocumentRenderOptions()):核心方法将指定页面渲染为QImage。metaData(QPdfDocument::MetaDataField field): 获取文档元数据如标题、作者。close(): 关闭文档释放资源。错误处理load方法返回QPdfDocument::Error枚举值应检查是否为QPdfDocument::Error::None。2.2、 QPdfDocumentRenderOptions用于精细控制页面渲染过程。常用设置setRenderFlags(QPdfDocumentRenderOptions::RenderFlags): 设置渲染标志例如RenderFlag::None: 默认。RenderFlag::Annotations: 渲染注释。RenderFlag::OptimizedForLcd: 为 LCD 屏幕优化。setScaledSize(QSize size): 设置渲染输出的目标尺寸像素。如果与pagePointSize比例不一致图像会被拉伸。2.3 、渲染流程与图像处理加载文档使用QPdfDocument::load。配置渲染创建QPdfDocumentRenderOptions对象并设置参数。执行渲染调用doc.render(pageIndex, targetSize, options)获得QImage。后处理得到的QImage可能包含透明背景对应PDF空白区域。如需白底可将其绘制到另一个填充了白色的QImage上如您分享的源码所示。设置DPI通过QImage::setDotsPerMeterX/Y()设置图像分辨率以控制打印或显示的物理尺寸精度。3、高级应用与注意事项多页处理循环pageCount()即可实现整个PDF的转换。性能优化渲染大尺寸或高DPI图像较耗时建议在后台线程进行。内存管理及时调用close()释放资源尤其是在批量处理时。与QPdfView集成对于需要交互式查看的场景直接使用QPdfView控件更为简单它内部封装了文档加载、渲染、缩放、导航等功能。文本提取QPdfDocument目前主要专注于渲染。如需复杂的文本提取、搜索功能可能需要结合其他库或等待Qt未来版本的增强。4、 核心类与API表格QPdfDocumentQPdfDocument是PDF文档的容器用于加载、解析和访问PDF内容。类别方法/枚举说明文档加载与状态Error load(const QString fileName)从文件加载PDF文档返回错误码。Error load(QIODevice *device)从IO设备加载PDF文档。void close()关闭当前文档释放资源。bool isLoaded() const返回文档是否已成功加载。Error error() const返回最后一次操作的错误码。QString errorString() const返回错误描述字符串。Status status() const返回文档的当前状态Null、Loading、Ready、Unloading、Error。页面信息int pageCount() const返回文档的总页数。QSizeF pagePointSize(int pageIndex) const返回指定页面的尺寸以点为单位1点1/72英寸。QSizeF pageSize(int pageIndex) const返回指定页面的尺寸以毫米为单位。QString metaData(QPdfDocument::MetaDataField field) const获取文档元数据如标题、作者、主题等。渲染QImage render(int pageIndex, const QSize imageSize, const QPdfDocumentRenderOptions options QPdfDocumentRenderOptions())将指定页面渲染为QImage。QImage render(int pageIndex, const QSizeF size, const QPdfDocumentRenderOptions options QPdfDocumentRenderOptions())重载版本接受QSizeF尺寸。导航与书签QPdfBookmarkModel *bookmarkModel() const返回书签模型用于文档导航。QPdfLinkModel *linkModel(int page) const返回指定页面的链接模型。信号void statusChanged(QPdfDocument::Status status)文档状态改变时发出。void pageCountChanged(int pageCount)页数改变时发出。void errorChanged(QPdfDocument::Error error, const QString description)发生错误时发出。void passwordRequired()需要密码解密时发出。QPdfDocumentRenderOptionsQPdfDocumentRenderOptions用于配置页面渲染的选项如缩放模式、旋转、裁剪等。选项方法说明缩放模式void setScaledClipRect(const QRectF rect)设置裁剪矩形相对于页面尺寸的比例0-1。QRectF scaledClipRect() const获取设置的裁剪矩形。void setScaledSize(const QSizeF size)设置渲染的目标尺寸以点为单位。QSizeF scaledSize() const获取目标尺寸。旋转void setRotation(QPdfDocumentRenderOptions::Rotation rotation)设置页面旋转角度0°、90°、180°、270°。Rotation rotation() const获取旋转设置。渲染标志void setRenderFlags(RenderFlags flags)设置渲染标志如反走样、文本反走样等。RenderFlags renderFlags() const获取渲染标志。颜色模式void setColorMode(ColorMode mode)设置颜色模式Color、Grayscale、Monochrome。ColorMode colorMode() const获取颜色模式。QPdfBookmarkModel用于表示PDF文档的书签目录结构通常与QTreeView等视图组件配合使用。方法说明QVariant data(const QModelIndex index, int role) const override获取书签项的数据如标题、页码。QModelIndex parent(const QModelIndex child) const override返回父节点的索引。int rowCount(const QModelIndex parent QModelIndex()) const override返回子项数量。int columnCount(const QModelIndex parent QModelIndex()) const override返回列数通常为1。QModelIndex index(int row, int column, const QModelIndex parent QModelIndex()) const override创建索引。QPdfLinkModel表示PDF页面中的链接超链接、文档内部跳转等。方法说明QVariant data(const QModelIndex index, int role) const override获取链接数据如URL、目标页码、矩形区域。int rowCount(const QModelIndex parent QModelIndex()) const override返回链接数量。QModelIndex parent(const QModelIndex child) const override返回父节点索引通常为无效索引。QModelIndex index(int row, int column, const QModelIndex parent QModelIndex()) const override创建索引。5. 总结Qt6 的 PDF 模块为桌面和嵌入式应用处理 PDF 提供了官方、高效的一站式解决方案。其核心在于QPdfDocument的加载与渲染能力。通过render()方法获取QImage后开发者可以灵活地进行后续的图像处理、保存或显示。本文详解了其核心类与典型工作流程并提供了可直接使用的代码示例。