大型物流公司每天都会收到大量来自不同供应商的货物运单 PDF 文件。这些运单包含了货物的详细信息,如发货人、收货人、货物名称、运输单号等。为了方便管理和后续的数据统计分析,物流公司需要对这些 PDF 运单进行处理,具体需求如下:
1、从每个 PDF 运单中提取运输单号作为文件名,对文件进行重命名,以便于快速定位和查找特定运单。2、将所有运单中的关键信息(如发货人、收货人、货物名称、运输单号)导出到一个 Excel 表格中,方便进行数据统计和分析。
要实现识别 PDF 区域内容并对文件进行改名处理,或者将内容导出到表格,可借助第三方库来完成。这里以Poppler
库进行 PDF 内容提取,LibXL
库进行表格数据导出为例,下面是详细的解决方案。
sudo apt-get install libpoppler-cpp-dev
)。使用Poppler
库打开 PDF 文件,提取指定区域的文本内容。
根据提取的内容对 PDF 文件进行重命名。
使用LibXL
库将提取的内容导出到 Excel 表格。
cpp
#include <iostream>
#include <string>
#include <poppler/cpp/poppler-document.h>
#include <poppler/cpp/poppler-page.h>
#include "libxl.h"
// 提取PDF指定区域的文本内容
std::string extractTextFromPDF(const std::string& filePath, double x, double y, double width, double height) {
poppler::document* doc = poppler::document::load_from_file(filePath);
if (!doc || doc->is_locked()) {
delete doc;
return "";
}
poppler::page* page = doc->create_page(0);
if (!page) {
delete doc;
return "";
}
poppler::rectf rect(x, y, x + width, y + height);
poppler::text_box_layout layout;
layout.set_rect(rect);
std::string text = page->text(layout).to_latin1();
delete page;
delete doc;
return text;
}
// 对文件进行重命名
bool renameFile(const std::string& oldPath, const std::string& newName) {
std::string newPath = oldPath.substr(0, oldPath.find_last_of("/\\") + 1) + newName + ".pdf";
return std::rename(oldPath.c_str(), newPath.c_str()) == 0;
}
// 将内容导出到Excel表格
bool exportToExcel(const std::string& filePath, const std::string& content) {
libxl::Book* book = xlCreateBook();
if (book) {
libxl::Sheet* sheet = book->addSheet("Sheet1");
if (sheet) {
sheet->writeStr(0, 0, content.c_str());
if (book->save(filePath.c_str())) {
book->release();
return true;
}
}
book->release();
}
return false;
}
int main() {
std::string pdfFilePath = "example.pdf";
// 假设提取区域的坐标和尺寸
double x = 100, y = 100, width = 200, height = 50;
// 提取指定区域的文本内容
std::string extractedText = extractTextFromPDF(pdfFilePath, x, y, width, height);
if (!extractedText.empty()) {
std::cout << "Extracted text: " << extractedText << std::endl;
// 对文件进行重命名
if (renameFile(pdfFilePath, extractedText)) {
std::cout << "File renamed successfully." << std::endl;
} else {
std::cerr << "Failed to rename file." << std::endl;
}
// 将内容导出到Excel表格
std::string excelFilePath = "output.xlsx";
if (exportToExcel(excelFilePath, extractedText)) {
std::cout << "Content exported to Excel successfully." << std::endl;
} else {
std::cerr << "Failed to export content to Excel." << std::endl;
}
} else {
std::cerr << "Failed to extract text from PDF." << std::endl;
}
return 0;
}
Poppler
库打开 PDF 文件,提取指定区域的文本内容。LibXL
库将提取的内容导出到 Excel 表格。编译时需要链接Poppler
和LibXL
库,示例命令如下:
sh
g++ -o pdf_processing pdf_processing.cpp -lpoppler-cpp -lxl
运行生成的可执行文件:
sh
./pdf_processing
Poppler
和LibXL
库已正确安装,并且编译器能够找到相应的头文件和库文件。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。