基于QT和百度云api實(shí)現(xiàn)批量獲取PDF局部文字內(nèi)容
應(yīng)用場(chǎng)景
1. 檔案管理
在企業(yè)或機(jī)構(gòu)的檔案管理中,常常會(huì)有大量的 PDF 格式的文件,如合同、報(bào)告、發(fā)票等。這些文件的原始文件名可能沒有明確的標(biāo)識(shí),不利于查找和管理。通過批量獲取 PDF 局部文字內(nèi)容并改名,可以根據(jù)文件中的關(guān)鍵信息(如合同編號(hào)、報(bào)告標(biāo)題等)為文件重新命名,提高檔案管理的效率。
2. 學(xué)術(shù)資料整理
在學(xué)術(shù)研究中,會(huì)收集大量的學(xué)術(shù)論文、研究報(bào)告等 PDF 文件。這些文件的文件名可能是隨機(jī)生成的或者不具有明確的主題信息。使用本方案可以提取 PDF 中的標(biāo)題、作者等關(guān)鍵信息,為文件重新命名,方便學(xué)者對(duì)學(xué)術(shù)資料進(jìn)行分類和檢索。
實(shí)現(xiàn)方案概述
本方案將使用 QT 構(gòu)建圖形用戶界面,結(jié)合百度云 OCR API 實(shí)現(xiàn)批量獲取 PDF 局部文字內(nèi)容并對(duì)文件進(jìn)行改名的功能。主要步驟包括:使用 QT 選擇 PDF 文件目錄,將 PDF 轉(zhuǎn)換為圖片(因?yàn)榘俣仍?OCR 主要處理圖片),指定局部區(qū)域進(jìn)行 OCR 識(shí)別,獲取識(shí)別結(jié)果作為新文件名,最后對(duì) PDF 文件進(jìn)行重命名。
準(zhǔn)備工作
注冊(cè)百度云賬號(hào):在百度云官網(wǎng)注冊(cè)賬號(hào)并創(chuàng)建 OCR 應(yīng)用,獲取 API Key 和 Secret Key。
安裝 QT:確保已經(jīng)安裝了 QT 開發(fā)環(huán)境。
安裝依賴庫(kù):需要安裝 Poppler 用于 PDF 轉(zhuǎn)圖片,以及 QNetworkAccessManager 用于網(wǎng)絡(luò)請(qǐng)求。
代碼實(shí)現(xiàn)
1. 創(chuàng)建 QT 項(xiàng)目
創(chuàng)建一個(gè)新的 QT Widgets Application 項(xiàng)目。
2. 界面設(shè)計(jì)
在 mainwindow.ui 中設(shè)計(jì)簡(jiǎn)單的界面,包含一個(gè)按鈕用于選擇 PDF 文件目錄,一個(gè)文本框用于顯示操作結(jié)果。
3. 代碼實(shí)現(xiàn)
cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QDir>
#include <QProcess>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QImage>
#include <QPixmap>
#include <QPainter>
#include <poppler/qt5/poppler-qt5.h>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->selectDirButton, &QPushButton::clicked, this, &MainWindow::selectDirectory);
networkManager = new QNetworkAccessManager(this);
connect(networkManager, &QNetworkAccessManager::finished, this, &MainWindow::onNetworkReplyFinished);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::selectDirectory()
{
QString dir = QFileDialog::getExistingDirectory(this, tr("Select Directory"), "", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (!dir.isEmpty()) {
QDir directory(dir);
QStringList filters;
filters << "*.pdf";
QStringList pdfFiles = directory.entryList(filters, QDir::Files);
for (const QString &pdfFile : pdfFiles) {
QString pdfPath = directory.filePath(pdfFile);
processPDF(pdfPath);
}
}
}
void MainWindow::processPDF(const QString &pdfPath)
{
Poppler::Document *document = Poppler::Document::load(pdfPath);
if (!document || document->isLocked()) {
ui->resultTextEdit->append("Failed to load PDF: " + pdfPath);
delete document;
return;
}
Poppler::Page *page = document->page(0);
if (!page) {
ui->resultTextEdit->append("Failed to get page from PDF: " + pdfPath);
delete document;
return;
}
QImage image = page->renderToImage();
// 假設(shè)我們要提取的局部區(qū)域(這里需要根據(jù)實(shí)際情況調(diào)整)
QRect region(100, 100, 200, 50);
QImage croppedImage = image.copy(region);
QByteArray imageData;
QBuffer buffer(&imageData);
buffer.open(QIODevice::WriteOnly);
croppedImage.save(&buffer, "JPEG");
buffer.close();
QString apiKey = "your_api_key";
QString secretKey = "your_secret_key";
QString tokenUrl = QString("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%1&client_secret=%2").arg(apiKey).arg(secretKey);
QNetworkRequest tokenRequest(QUrl(tokenUrl));
networkManager->get(tokenRequest);
pdfPaths.append(pdfPath);
imageDatas.append(imageData);
delete page;
delete document;
}
void MainWindow::onNetworkReplyFinished(QNetworkReply *reply)
{
if (reply->error() == QNetworkReply::NoError) {
QByteArray responseData = reply->readAll();
QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);
QJsonObject jsonObj = jsonDoc.object();
if (jsonObj.contains("access_token")) {
QString accessToken = jsonObj["access_token"].toString();
if (!pdfPaths.isEmpty() && !imageDatas.isEmpty()) {
QString pdfPath = pdfPaths.takeFirst();
QByteArray imageData = imageDatas.takeFirst();
QString ocrUrl = QString("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=%1").arg(accessToken);
QNetworkRequest ocrRequest(QUrl(ocrUrl));
ocrRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QByteArray postData;
postData.append("image=").append(QUrl::toPercentEncoding(imageData.toBase64()));
networkManager->post(ocrRequest, postData);
}
} else if (jsonObj.contains("words_result")) {
QJsonArray wordsResult = jsonObj["words_result"].toArray();
QString newFileName;
for (const auto &result : wordsResult) {
QJsonObject wordObj = result.toObject();
newFileName += wordObj["words"].toString();
}
if (!pdfPaths.isEmpty()) {
QString pdfPath = pdfPaths.takeFirst();
QFileInfo fileInfo(pdfPath);
QString newFilePath = fileInfo.dir().filePath(newFileName + ".pdf");
QFile::rename(pdfPath, newFilePath);
ui->resultTextEdit->append("Renamed: " + pdfPath + " to " + newFilePath);
}
}
} else {
ui->resultTextEdit->append("Network error: " + reply->errorString());
}
reply->deleteLater();
}4. 頭文件 mainwindow.h
cpp
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QNetworkAccessManager>
#include <QList>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void selectDirectory();
void onNetworkReplyFinished(QNetworkReply *reply);
private:
Ui::MainWindow *ui;
QNetworkAccessManager *networkManager;
QList<QString> pdfPaths;
QList<QByteArray> imageDatas;
void processPDF(const QString &pdfPath);
};
#endif // MAINWINDOW_H

注意事項(xiàng)
請(qǐng)將 your_api_key 和 your_secret_key 替換為你自己的百度云 OCR API Key 和 Secret Key。
代碼中假設(shè)要提取的局部區(qū)域?yàn)?nbsp;QRect(100, 100, 200, 50),你需要根據(jù)實(shí)際情況
以上就是基于QT和百度云api實(shí)現(xiàn)批量獲取PDF局部文字內(nèi)容的詳細(xì)內(nèi)容,更多關(guān)于QT獲取PDF局部?jī)?nèi)容的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C語言中關(guān)于庫(kù)函數(shù) qsort 快排的用法
快速排序Qsort是所有學(xué)習(xí)算法和數(shù)據(jù)結(jié)構(gòu)最基礎(chǔ)的一個(gè)部分,也是考試題和面試的一個(gè)小重點(diǎn)。本片文章帶你了解Qsort的詳細(xì)用法規(guī)則2021-09-09
C語言代碼實(shí)現(xiàn)學(xué)生成績(jī)管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C語言代碼實(shí)現(xiàn)學(xué)生成績(jī)管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-06-06
C++如何動(dòng)態(tài)的生成對(duì)象詳解
C++是不支持根據(jù)類名動(dòng)態(tài)地生成對(duì)象的,比如從一個(gè)文本文件中讀取類名然后構(gòu)造一個(gè)對(duì)象.主要原因是沒有豐富的動(dòng)態(tài)元信息,沒有單根類庫(kù)。那么下面這篇文章就來給大家介紹C++是如何動(dòng)態(tài)的生成對(duì)象,有需要的朋友們可以參考借鑒。2017-02-02
C語言驅(qū)動(dòng)開發(fā)之內(nèi)核通過PEB獲取進(jìn)程參數(shù)
PEB結(jié)構(gòu)(Process Envirorment Block Structure)其中文名是進(jìn)程環(huán)境塊信息。本文將通過PEB實(shí)現(xiàn)獲取進(jìn)程參數(shù),感興趣的小伙伴可以了解一下2022-10-10
C語言實(shí)現(xiàn)BMP圖像處理(直方圖均衡化)
這篇文章主要為大家詳細(xì)介紹了C語言實(shí)現(xiàn)BMP圖像直方圖均衡化處理,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-10-10
C++實(shí)現(xiàn)LeetCode(904.水果裝入果籃)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(904.水果裝入果籃),本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07

