跳至頁尾內容
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. 您的系統上已安裝 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...
}
$vbLabelText   $csharpLabel

有關如何閱讀 PDF 文件的更多詳細信息,請訪問IronPDF C# PDF 閱讀指南

結論

在本文中,我們學習如何使用 Xpdf 命令列工具在 C++ 中讀取 PDF 文件的內容。 透過將 Xpdf 整合到 C++ 程式中,我們可以在幾秒鐘內以程式設計方式從 PDF 檔案中提取文字內容。 這種方法使我們能夠在 C++ 應用程式中處理和分析提取的文字。

IronPDF是一個功能強大的 C# 庫,可以輕鬆讀取和操作 PDF 文件。 它豐富的功能、易用性和可靠的渲染引擎使其成為在 C# 專案中處理 PDF 文件的開發人員的熱門選擇。

IronPDF 可供開發使用,並提供免費試用版供商業用途使用。 除此之外,它還需要商業用途的許可

柯蒂斯·週
技術撰稿人

Curtis Chau擁有卡爾頓大學電腦科學學士學位,專長於前端開發,精通Node.js、TypeScript、JavaScript和React。他熱衷於打造直覺美觀的使用者介面,喜歡使用現代框架,並擅長撰寫結構清晰、視覺效果出色的使用者手冊。

除了開發工作之外,柯蒂斯對物聯網 (IoT) 也抱有濃厚的興趣,致力於探索硬體和軟體整合的創新方法。閒暇時,他喜歡玩遊戲和製作 Discord 機器人,將他對科技的熱愛與創造力結合。