跳過到頁腳內容
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的一些關鍵組件包括pdfimagespdftopspdfinfo,和pdftotext。 在這裡,我們將使用pdftotext來讀取PDF文件。

pdftotext是一個命令行工具,可以從PDF文件中提取文本內容,並將其作為純文本輸出。 當需要從PDF中提取文本信息進行進一步處理或分析時,這個工具特別有用。 使用選項,你還可以指定要提取文本的頁面或頁數。

準備工作

要製作一個PDF讀取項目來提取文本,我們需要具備以下前提條件:

  1. 安裝在您的系統上的 C++ 編譯器,例如 GCC 或 Clang。 您可以使用任何支持 C++ 編程的 IDE。
  2. 系統上已安裝Xpdf命令行工具。 Xpdf是一個PDF工具集合,可以從Xpdf網站獲得。從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++代碼

讓我們編寫C++代碼,以調用Xpdf命令行工具從PDF文件中提取文本內容。 我們要使用以下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文件是一個簡單的過程。 該庫提供了多種方法和屬性,允許開發人員從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 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

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