跳過到頁腳內容
PDF工具

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

由於 PDF 文件能夠在不同平台上保持格式一致,因此成為文件交換中廣泛使用的格式。 在各種應用程式中,程序化地讀取 PDF 文件的內容變得非常有價值。

在本文中,我們將學習如何使用 Xpdf 命令行工具在 C++ 中查看 PDF 文件中的文字。 Xpdf 提供了一套命令行工具和 C++ 函式庫,用於處理 PDF 文件,包括文字提取。 通過將 Xpdf 集成到我們的 C++ PDF 檢視器程式中,我們可以有效地查看 PDF 文件中的文字內容,並以程式方式進行處理。

Xpdf - C++函式庫及命令行工具

Xpdf 是一套開源軟體套裝,提供了一系列工具和函式庫用於處理 PDF 文件。 它包括各種命令行工具和 C++ 函式庫,可實現 PDF 相關功能,如解析、渲染、列印和文字提取。 Xpdf 的命令行工具還提供了從終端直接查看 PDF 文件的方法。

Xpdf 的關鍵組件之一是 pdftotext,主要用於從 PDF 文件中提取文字內容。 然而,當與其他工具如 pdftopspdfimages 結合使用時,Xpdf 允許用戶以不同方式查看 PDF 內容。 pdftotext 工具在從 PDF 中提取文字資訊以進一步處理或分析方面非常有價值,它提供了指定需提取文字的頁面的選項。

準備工作

在開始之前,確保您具備以下必要條件:

  1. 安裝在您的系統上的 C++ 編譯器,例如 GCC 或 Clang。 我們將使用 Code::Blocks IDE 來完成這一目的。
  2. Xpdf 命令行工具已安裝並可從命令行訪問。 下載 Xpdf 並安裝適合您環境的版本。 之後,在系統環境變數路徑中設置 Xpdf 的 bin 目錄,以便從文件系統中的任何位置訪問。

創建 PDF 檢視器專案

  1. 打開 Code::Blocks: 在電腦上啟動 Code::Blocks IDE。
  2. 建立新專案:從頂部菜單單擊“文件”,並從下拉菜單中選擇“新建”。 然後從子選單中單擊“專案”。
  3. 選擇專案類型:在“從範本新建”窗口中,選擇“控制台應用程式”,然後單擊“前往”。 然後選擇語言“C/C++”,然後單擊“下一步”。
  4. 輸入專案詳細資訊:在“專案標題”欄中,為您的專案命名(例如,“PDFViewer”)。 選擇您想要保存專案文件的位置,然後單擊“下一步”。
  5. 選擇編譯器:選擇您要用於專案的編譯器。 默認情況下,Code::Blocks 應自動偵測到系統上可用的編譯器。 如果沒有,從列表中選擇合適的編譯器,然後單擊“完成”。

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# 函式庫 是一種功能強大的 .NET C# PDF 函式庫,允許用戶在其 C# 應用程式中輕鬆查看 PDF 文件。 IronPDF 利用 Chromium 網頁瀏覽器引擎,準確地渲染並顯示 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 中,轉到“工具” > “NuGet 軟體包管理器” > “管理解決方案的 NuGet 軟體包”。 或者,點擊解決方案資源管理器,然後選擇“管理解決方案的 NuGet 軟體包”。
  4. 搜索 IronPDF:在“NuGet 軟體包管理器”窗口中,點擊“瀏覽”選項卡,然後在搜索欄中搜索“IronPDF”。 或者,訪問 NuGet IronPDF 軟體包 並直接下載最新版本的“IronPDF”。
  5. 選擇 IronPDF 軟體包:找到“鐵 PDF” 軟體包,然後點擊它以選擇您的專案。
  6. 安裝 IronPDF:點擊“安裝”按鈕來安裝選中的軟體包。
  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 文件

結論

在本文中,我們學習了如何使用 Xpdf 命令行工具在 C++ 中提取和查看 PDF 文件的內容。 這種方法使我們可以在 C++ 應用程式中無縫地處理和分析提取的文字。

可以獲得免費試用許可證以用於商業目的的測試。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。