跳至页脚内容
PDF 工具

如何在 C++ 中查看 PDF 文件

PDF 文件是一种广泛使用的文档交换格式,因为它能够跨不同平台保持格式。 在各种应用程序中,编程方式读取 PDF 文件的内容变得非常宝贵。

在本文中,我们将学习如何使用 Xpdf 命令行工具在 C++ 中查看 PDF 文件中的文本。 Xpdf 提供了一套用于处理 PDF 文件的命令行实用程序和 C++ 库,包括文本提取。 通过将 Xpdf 集成到我们的 C++ PDF 查看程序中,我们可以有效地查看 PDF 文件的文本内容并以编程方式处理。

Xpdf - C++ 库和命令行工具

Xpdf 是一个开源软件套件,提供一系列用于处理 PDF 文件的工具和库。 它包括各种命令行实用程序和 C++ 库,使 PDF 相关功能成为可能,例如解析、渲染、打印和文本提取。 Xpdf 的命令行工具还提供直接从终端查看 PDF 文件的方法。

Xpdf 的关键组件之一是 pdftotext,它主要以从 PDF 文件中提取文本内容而闻名。 然而,结合使用其他工具如 pdftopspdfimagesXpdf 允许用户以不同方式查看 PDF 内容。 pdftotext 工具对从 PDF 中提取文本信息以供进一步处理或分析非常有价值,并提供选项以指定从哪些页面提取文本。

前提条件

在我们开始之前,请确保你已具备以下先决条件:

  1. 在您的系统上安装诸如 GCC 或 Clang 的 C++ 编译器。 我们将为此目的使用 Code::Blocks IDE
  2. 已安装 Xpdf 命令行工具并可以从命令行访问。下载 Xpdf 并安装适合您环境的版本。 然后,在系统环境变量路径中设置 Xpdf 的 bin 目录,以便可以从文件系统的任何位置进行访问。

创建 PDF 查看器项目

  1. 打开 Code::Blocks: 在您的计算机上启动 Code::Blocks IDE。
  2. 创建新项目: 从顶部菜单中点击 "File" 并从下拉菜单中选择 "New"。 然后,从子菜单中点击 "Project"。
  3. 选择项目类型: 在 "New from template" 窗口中,选择 "Console application",然后点击 "Go"。 然后选择语言 "C/C++" 并点击 "Next"。
  4. 输入项目详细信息: 在 "Project title" 字段中,为项目命名(例如,"PDFViewer")。 选择要保存项目文件的位置,然后点击 "Next"。
  5. 选择编译器: 选择要用于项目的编译器。 默认情况下,Code::Blocks 应该已经自动检测到系统中可用的编译器。 如果没有,请从列表中选择一个合适的编译器,然后点击 "Finish"。

在 C++ 中查看 PDF 文本的步骤

包含必要的头文件

首先,让我们将所需的头文件添加到我们的 main.cpp 文件中:

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

using namespace std; // Use standard namespace for convenience
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cstdio>

using namespace std; // Use standard namespace for convenience
C++

设置输入和输出路径

string pdfPath = "input.pdf";
string outputFilePath = "output.txt";
string pdfPath = "input.pdf";
string outputFilePath = "output.txt";
C++

main 函数中,我们声明两个字符串:pdfPathoutputFilePathpdfPath 存储输入 PDF 文件的路径,outputFilePath 存储提取的文本将保存为纯文本文件的位置。

输入文件如下:

如何在 C++ 中查看 PDF 文件:图 1

执行 pdftotext 命令

// Construct the command to execute pdftotext with input and output paths
string command = "pdftotext " + pdfPath + " " + outputFilePath;

// Execute the command using system function and capture the status
int status = system(command.c_str());
// Construct the command to execute pdftotext with input and output paths
string command = "pdftotext " + pdfPath + " " + outputFilePath;

// Execute the command using system function and capture the status
int status = system(command.c_str());
C++

在这里,我们使用 pdfPathoutputFilePath 变量构建 pdftotext 命令以打开 PDF 文件查看其内容。 然后调用 system 函数执行该命令,并将其返回值存储在 status 变量中。

检查文本提取状态

if (status == 0) 
{
    cout << "Text extraction successful." << endl;
} 
else 
{ 
    cout << "Text extraction failed." << endl; 
}
if (status == 0) 
{
    cout << "Text extraction successful." << endl;
} 
else 
{ 
    cout << "Text extraction failed." << endl; 
}
C++

我们检查 status 变量以查看 pdftotext 命令是否成功执行。 如果 status 等于 0,表示文本提取成功,我们打印成功消息。 如果 status 为非零,表示错误,我们打印错误消息。

读取提取的文本并显示

// 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"; // Concatenate each line to the text content
    }
    outputFile.close();
    cout << "Text content extracted from PDF:" << endl;
    cout << textContent << endl;
} 
else 
{
    cout << "Failed to open output file." << endl;
}
// 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"; // Concatenate each line to the text content
    }
    outputFile.close();
    cout << "Text content extracted from PDF:" << endl;
    cout << textContent << endl;
} 
else 
{
    cout << "Failed to open output file." << endl;
}
C++

在上面的示例代码中,我们打开 outputFile(由 pdftotext 生成的文本文件),逐行读取其内容,并将其存储在 textContent 字符串中。 最后,我们关闭文件并在控制台上打印提取的文本内容。

删除输出文件

如果您不需要可编辑的输出文本文件或希望释放磁盘空间,在程序结束时在结束主函数之前使用以下命令简单地删除它:

// Remove the output file to free up disk space and if output is not needed
remove(outputFilePath.c_str());
// Remove the output file to free up disk space and if output is not needed
remove(outputFilePath.c_str());
C++

编译和运行程序

使用 "Ctrl+F9" 快捷键构建代码。 成功编译后,运行可执行文件将从指定的 PDF 文档中提取文本内容并显示在控制台上。 译文如下:

如何在 C++ 中查看 PDF 文件:图 2

在 C# 中查看 PDF 文件

IronPDF .NET C# Library 是一个强大的 .NET C# PDF 库,允许用户轻松地在其 C# 应用程序中查看 PDF 文件。 利用 Chromium Web 浏览器引擎,IronPDF 准确渲染和显示 PDF 内容,包括图像、字体和复杂格式。 借助其用户友好的界面和广泛的功能,开发人员可以将 IronPDF 无缝集成到其 C# 项目中,使用户能够有效、互动地查看 PDF 文档。 无论是用于显示报告、发票,还是任何其他 PDF 内容,IronPDF 都为创建功能丰富的 C# PDF 查看器提供了坚实的解决方案。

要在 Visual Studio 中安装 IronPDF NuGet 包,请按以下步骤操作:

  1. 打开 Visual Studio: 启动 Visual Studio 或任何您偏好的 IDE。
  2. 创建或打开项目: 创建一个新的 C# 项目或打开一个您想要安装 IronPDF 包的现有项目。
  3. 打开 NuGet 包管理器: 在 Visual Studio 中,转到 "Tools" > "NuGet Package Manager" > "Manage NuGet Packages for Solution"。 或者,单击解决方案资源管理器,然后选择 "Manage NuGet Packages for Solution"。
  4. 搜索 IronPDF: 在 "NuGet Package Manager" 窗口中,点击 "Browse" 选项卡,然后在搜索栏中搜索 "IronPDF"。 或者,访问 NuGet IronPDF Package 并直接下载最新版本的 "IronPDF"。
  5. 选择 IronPDF 包: 找到 "IronPDF" 包并点击选择您的项目。
  6. 安装 IronPDF: 点击 "Install" 按钮安装所选包。
  7. 您还可以使用以下命令在 NuGet 包管理器控制台中安装 IronPDF:

    Install-Package IronPdf

使用 IronPDF,我们可以执行操作,例如从 PDF 文档中提取文本和图像并在控制台中显示它们以供查看。 以下代码有助于完成这一任务:

using IronPdf;
using IronSoftware.Drawing;
using System.Collections.Generic;

// Extracting Image and Text content from Pdf Documents
// Open a 128-bit encrypted PDF
var pdf = PdfDocument.FromFile("encrypted.pdf", "password");

// Get all text to put in a search index
string text = pdf.ExtractAllText();

// Get all Images
var allImages = pdf.ExtractAllImages();

// Or even find the precise text and images for each page in the document
for (var index = 0 ; index < pdf.PageCount ; index++)
{
    int pageNumber = index + 1;
    text = pdf.ExtractTextFromPage(index);
    List<AnyBitmap> images = pdf.ExtractBitmapsFromPage(index);
    // Further processing here...
}
using IronPdf;
using IronSoftware.Drawing;
using System.Collections.Generic;

// Extracting Image and Text content from Pdf Documents
// Open a 128-bit encrypted PDF
var pdf = PdfDocument.FromFile("encrypted.pdf", "password");

// Get all text to put in a search index
string text = pdf.ExtractAllText();

// Get all Images
var allImages = pdf.ExtractAllImages();

// Or even find the precise text and images for each page in the document
for (var index = 0 ; index < pdf.PageCount ; index++)
{
    int pageNumber = index + 1;
    text = pdf.ExtractTextFromPage(index);
    List<AnyBitmap> images = pdf.ExtractBitmapsFromPage(index);
    // Further processing here...
}
Imports IronPdf
Imports IronSoftware.Drawing
Imports System.Collections.Generic

' Extracting Image and Text content from Pdf Documents
' Open a 128-bit encrypted PDF
Private pdf = PdfDocument.FromFile("encrypted.pdf", "password")

' Get all text to put in a search index
Private text As String = pdf.ExtractAllText()

' Get all Images
Private allImages = pdf.ExtractAllImages()

' Or even find the precise text and images for each page in the document
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)
	' Further processing here...
Next index
$vbLabelText   $csharpLabel

有关 IronPDF 的更多详细信息,请访问 IronPDF Documentation

结论

在本文中,我们学习了如何使用 Xpdf 命令行工具提取和查看 PDF 文档的内容。 这种方法使我们能够在 C++ 应用程序中无缝地处理和分析提取的文本。

提供一个免费试用许可以用于商业目的的测试。

Curtis Chau
技术作家

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

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