跳至页脚内容
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 生成的输出文本文件的路径。

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

如果 pdftotext 成功执行(状态为 0),我们继续使用 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...
}
' Import necessary namespaces
Imports IronPdf ' For PDF functionalities
Imports IronSoftware.Drawing ' For handling images
Imports System.Collections.Generic ' For using the List

' Example of extracting text and images from PDF using IronPDF

' Open a 128-bit encrypted PDF
Private pdf = PdfDocument.FromFile("encrypted.pdf", "password")

' Get all text from the PDF
Private text As String = pdf.ExtractAllText()

' Extract all images from the PDF
Private allImages = pdf.ExtractAllImages()

' Iterate over each page to extract text and images
For index = 0 To pdf.PageCount - 1
	Dim pageNumber As Integer = index + 1
	text = pdf.ExtractTextFromPage(index)
	Dim images As List(Of AnyBitmap) = pdf.ExtractBitmapsFromPage(index)
	' Perform actions with text and images...
Next index
$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 机器人,将他对技术的热爱与创造力相结合。