在处理 Word 文档时,我们经常需要提取其中的文字和图片来创建新的文档或是用于其他用途。如果我们手动复制文字或逐一保存图片,将会非常耗时且容易出现错误或遗漏的情况。本文将介绍如何使用 Spire.Doc for C++ 通过程序快速 Word 文档中提取文字和图片。
安装 Spire.Doc for C++
有两种方法可以将 Spire.Doc for C++ 集成到您的应用程序中。一种方法是通过 NuGet 安装它,另一种方法是从我们的网站下载包并将库复制到您的程序中。通过 NuGet 安装更简单,更推荐使用。您可以通过访问以下链接找到更多详细信息。
如何将 Spire.Doc for C++ 集成到 C++ 程序中
从 Word 文档中提取文本
Spire.Doc for C++ 中的 Document->GetText() 方法可以获取一个 Word 文档中的所有文本内容。以下是提取 Word 文档中的文本并保存为 TXT 文件的详细操作步骤:
- 创建 Document 的对象。
- 使用 Document->LoadFromFile() 方法载入 Word 文档。
- 使用 Document->GetText() 方法获取文档的所有文本内容。
- 创建一个 TXT 文件并将提取的文本内容写入其中。
- C++
#include "Spire.Doc.o.h"
#include <iostream>
#include <locale>
#include <codecvt>
using namespace Spire::Doc;
using namespace std;
int main()
{
//创建Document的对象
intrusive_ptr document = new Document();
//载入Word文档
document->LoadFromFile(L""C:/宇宙视角.docx"");
//获取文档中的文本内容
wstring text = document->GetText();
//创建一个TXT文件并将提取的文本内容写入其中
wofstream write(L""Output/提取文本.txt"");
auto LocUtf8 = locale(locale(""""), new std::codecvt_utf8);
write.imbue(LocUtf8);
write << text;
write.close();
document->Close();
} 
从 Word 文档中提取图片
提取 Word 文档中的图片需要判断文档的每个子对象是否为图片,再用 DocPicture->GetImage() 提取图片。以下是详细操作步骤:
- 创建 Document 的对象。
- 使用 Document->LoadFromFile() 方法载入 Word 文档。
- 将文档附加到 deque 队列的末尾,然后创建一个矢量图像列表。
- 循环遍历文档的所有子对象,判断每个子对象是否为图片。如果是,则使用 DocPicture->GetImage() 方法获取该图片并添加到列表中。
- 将提取的图片储存到指定路径。
- C++
#include ""Spire.Doc.o.h""
#include
using namespace std;
using namespace Spire::Doc;
int main() {
//创建Document的对象
intrusive_ptr document = new Document();
//载入Word文档
document->LoadFromFile(L""C:/宇宙视角.docx"");
//document elements, each of them has child elements
std::deque> nodes;
nodes.push_back(document);
//embedded images list.
std::vector> images;
//traverse
while (nodes.size() > 0)
{
intrusive_ptr node = nodes.front();
nodes.pop_front();
for (int i = 0; i < node->GetChildObjects()->GetCount(); i++)
{
intrusive_ptr child = node->GetChildObjects()->GetItem(i);
if (child->GetDocumentObjectType() == DocumentObjectType::Picture)
{
intrusive_ptr picture = Object::Dynamic_cast(child);
std::vector imageByte = picture->GetImageBytes();
images.push_back(imageByte);
}
else if (Object::CheckType(child))
{
nodes.push_back(boost::dynamic_pointer_cast(child));
}
}
}
//save images
for (size_t i = 0; i < images.size(); i++)
{
std::wstring fileName = L""图像-"" + std::to_wstring(i) + L"".png"";
std::ofstream outFile(fileName, std::ios::binary);
if (outFile.is_open())
{
outFile.write(reinterpret_cast(images[i].data()), images[i].size());
outFile.close();
}
}
document->Close();
}
} 
申请临时 License
如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。







