跳至页脚内容
PDF 工具

如何在 C++ 中读取 PDF 文件

PDF(可移植文档格式)文件广泛用于文档交换,能够以编程方式读取其内容在各种应用中具有价值。 以下库可用于在 C++ 中读取 PDF:Poppler、MuPDF、Haru 免费 PDF 库、Xpdf 和 Qpdf。

在本文中,我们将探讨如何使用 Xpdf 命令行工具在 C++ 中读取 PDF 文件。 Xpdf 提供了一系列用于处理 PDF 文件的实用工具,包括提取文本内容。 通过将 Xpdf 集成到 C++ 程序中,我们可以从 PDF 文件中提取文本,并以编程方式处理它。

Xpdf - 命令行工具

Xpdf 是一个开源软件套件,提供了用于处理 PDF(可移植文档格式)文件的工具和库集合。 Xpdf 套件包括几个命令行实用程序和 C++ 库,可实现各种 PDF 相关功能,如解析、渲染、文本提取等。 Xpdf 的一些关键组件包括 pdfimagespdftopspdfinfopdftotext。 在这里,我们将使用pdftotext来读取PDF文档。

pdftotext是一个命令行工具,它从PDF文件中提取文本内容并将其输出为纯文本。 当您需要从 PDF 提取文本信息以进行进一步处理或分析时,此工具特别实用。 使用选项,您还可以指定要从中提取文本的页面。

前提条件

要制作一个提取文本的 PDF 阅读器项目,我们需要满足以下先决条件:

  1. 在您的系统上安装诸如 GCC 或 Clang 的 C++ 编译器。 您可以使用任何支持 C++ 编程的 IDE。
  2. 在您的系统上安装 Xpdf 命令行工具。 Xpdf 是一组可以从 Xpdf 网站获取的 PDF 实用程序。从 Xpdf 网站 下载。 在环境变量路径中设置 Xpdf 的 bin 目录,以便可以使用命令行工具从任何地方访问它。

C++ 中读取 PDF 文件格式的步骤

步骤 1: 包含必要的头文件

首先,让我们在我们的main.cpp文件顶部添加必要的头文件:

#include <cstdlib>  // For system call
#include <iostream> // For basic input and output
#include <fstream>  // For file stream operations
#include <cstdlib>  // For system call
#include <iostream> // For basic input and output
#include <fstream>  // For file stream operations
C++

步骤 2: 编写 C++ 代码

让我们编写调用 Xpdf 命令行工具以从 PDF 文档中提取文本内容的 C++ 代码。 我们将使用以下input.pdf文件:

如何在C++中读取PDF文件:图1

代码示例如下:

#include <cstdlib>
#include <iostream>
#include <fstream>

using namespace std;

int main() {
    // Specify the input and output file paths
    string pdfPath = "input.pdf";
    string outputFilePath = "output.txt";

    // Construct the command to run pdftotext
    string command = "pdftotext " + pdfPath + " " + outputFilePath;
    int status = system(command.c_str());

    // Check if the command executed successfully
    if (status == 0) {
        cout << "Text extraction successful." << endl;
    } else {
        cout << "Text extraction failed." << endl;
        return 1; // Exit the program with error code
    }

    // Open the output file to read the extracted text
    ifstream outputFile(outputFilePath);
    if (outputFile.is_open()) {
        string textContent;
        string line;
        while (getline(outputFile, line)) {
            textContent += line + "\n"; // Append each line to the textContent
        }
        outputFile.close();

        // Display the extracted text
        cout << "Text content extracted from PDF document:" << endl;
        cout << textContent << endl;
    } else {
        cout << "Failed to open output file." << endl;
        return 1; // Exit the program with error code
    }

    return 0; // Exit the program successfully
}
#include <cstdlib>
#include <iostream>
#include <fstream>

using namespace std;

int main() {
    // Specify the input and output file paths
    string pdfPath = "input.pdf";
    string outputFilePath = "output.txt";

    // Construct the command to run pdftotext
    string command = "pdftotext " + pdfPath + " " + outputFilePath;
    int status = system(command.c_str());

    // Check if the command executed successfully
    if (status == 0) {
        cout << "Text extraction successful." << endl;
    } else {
        cout << "Text extraction failed." << endl;
        return 1; // Exit the program with error code
    }

    // Open the output file to read the extracted text
    ifstream outputFile(outputFilePath);
    if (outputFile.is_open()) {
        string textContent;
        string line;
        while (getline(outputFile, line)) {
            textContent += line + "\n"; // Append each line to the textContent
        }
        outputFile.close();

        // Display the extracted text
        cout << "Text content extracted from PDF document:" << endl;
        cout << textContent << endl;
    } else {
        cout << "Failed to open output file." << endl;
        return 1; // Exit the program with error code
    }

    return 0; // Exit the program successfully
}
C++

代码解释

在上述代码中,我们定义了pdfPath变量来保存输入PDF文件的路径。请确保将其替换为您实际输入的PDF文档的适当路径。

我们还定义了outputFilePath变量以保存将由Xpdf生成的输出文本文件的路径。

该代码使用pdftotext命令,将输入PDF文件路径和输出文本文件路径作为命令行参数传递。 status变量捕获命令的退出状态。

如果ifstream打开输出文本文件。 然后我们逐行读取文本内容并将其存储在textContent字符串中。

最后,我们将从生成的输出文件中提取的文本内容输出到控制台。 如果您不需要可编辑的输出文本文件或希望释放磁盘空间,在程序结束时在结束主函数之前使用以下命令简单地删除它:

remove(outputFilePath.c_str());
remove(outputFilePath.c_str());
C++

步骤 3: 编译和运行程序

编译 C++ 代码并运行可执行文件。 如果将pdftotext添加到环境变量系统路径中,其命令将成功执行。 程序生成输出文本文件并从 PDF 文档中提取文本内容。 提取的文本随后显示在控制台上。

输出如下所示

如何在C++中读取PDF文件:图2

在 C# 中读取 PDF 文件

IronPDF 库

IronPDF 是一个流行的 C# PDF 库,提供强大的功能来处理 PDF 文档。 它使开发人员能够以编程方式创建、编辑、修改和读取 PDF 文件。

使用 IronPDF 库读取 PDF 文档是一个简单的过程。 该库提供了各种方法和属性,使开发人员能够提取文本、图像、元数据和其他数据。 提取的信息可用于进一步处理、分析或在应用程序中显示。

以下代码示例将 使用 IronPDF 读取 PDF 文件

// Import necessary namespaces
using IronPdf; // For PDF functionalities
using IronSoftware.Drawing; // For handling images
using System.Collections.Generic; // For using the List

// Example of extracting text and images from PDF using IronPDF

// Open a 128-bit encrypted PDF
var pdf = PdfDocument.FromFile("encrypted.pdf", "password");

// Get all text from the PDF
string text = pdf.ExtractAllText();

// Extract all images from the PDF
var allImages = pdf.ExtractAllImages();

// Iterate over each page to extract text and images
for (var index = 0; index < pdf.PageCount; index++) {
    int pageNumber = index + 1;
    text = pdf.ExtractTextFromPage(index);
    List<AnyBitmap> images = pdf.ExtractBitmapsFromPage(index);
    // Perform actions with text and images...
}
// Import necessary namespaces
using IronPdf; // For PDF functionalities
using IronSoftware.Drawing; // For handling images
using System.Collections.Generic; // For using the List

// Example of extracting text and images from PDF using IronPDF

// Open a 128-bit encrypted PDF
var pdf = PdfDocument.FromFile("encrypted.pdf", "password");

// Get all text from the PDF
string text = pdf.ExtractAllText();

// Extract all images from the PDF
var allImages = pdf.ExtractAllImages();

// Iterate over each page to extract text and images
for (var index = 0; index < pdf.PageCount; index++) {
    int pageNumber = index + 1;
    text = pdf.ExtractTextFromPage(index);
    List<AnyBitmap> images = pdf.ExtractBitmapsFromPage(index);
    // Perform actions with text and images...
}
$vbLabelText   $csharpLabel

有关如何读取 PDF 文档的更多详细信息,请访问 IronPDF C# PDF 阅读指南

结论

在本文中,我们学习了如何使用 Xpdf 命令行工具在 C++ 中读取 PDF 文档的内容。 通过将 Xpdf 集成到 C++ 程序中,我们可以在几秒钟内以编程方式从 PDF 文件中提取文本内容。 这种方法使我们能够在 C++ 应用程序中处理和分析提取的文本。

IronPDF 是一个强大的 C# 库,方便读取和操作 PDF 文件。 其广泛的功能、易用性和可靠的渲染引擎使其成为开发人员在 C# 项目中处理 PDF 文档的热门选择。

IronPDF 免费用于开发,并提供 商业用途的免费试用。 除此之外,它需要获得商业许可

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me