フッターコンテンツにスキップ
PDF ツール

C++でPDFファイルを表示する方法

PDFファイルは、異なるプラットフォーム間でフォーマットを保持できるため、ドキュメント交換のために広く使用されているフォーマットです。 さまざまなアプリケーションでは、プログラムでPDFファイルの内容を読み取ることが非常に価値があります。

この記事では、Xpdfコマンドラインツールを使用して、C++でPDFファイルからテキストを表示する方法を学びます。 Xpdfは、PDFファイルでテキストを抽出するためのコマンドラインユーティリティとC++ライブラリのスイートを提供します。 XpdfをC++PDFビューアプログラムに統合することで、PDFファイルからテキストコンテンツを効率的に表示し、プログラムで処理することができます。

Xpdf - C++ライブラリとコマンドラインツール

Xpdfは、PDFファイルを操作するためのツールとライブラリの範囲を提供するオープンソースのソフトウェアスイートです。 PDF関連の機能を有効にするさまざまなコマンドラインユーティリティとC++ライブラリが含まれており、解析、レンダリング、印刷、テキスト抽出などを行うことが可能です。 Xpdfのコマンドラインツールは、ターミナルから直接PDFファイルを表示する方法も提供しています。

Xpdfの主要コンポーネントの1つであるpdftotextは、主にPDFファイルからテキストコンテンツを抽出することで知られています。 しかし、pdftopspdfimagesなどの他のツールと組み合わせることで、XpdfはPDFコンテンツを別の方法で表示することができます。 pdftotextツールは、PDFからテキスト情報を抽出してさらに処理または分析するために非常に価値があり、どのページからテキストを抽出するかを指定するオプションを提供します。

前提条件

始める前に、次の前提条件が整っていることを確認してください。

  1. システムにGCCやClangなどのC++コンパイラがインストールされていること。 この目的のために、Code::Blocks IDEを使用します。
  2. コマンドラインからアクセス可能なXpdfコマンドラインツールをインストールします。Xpdfをダウンロードして、環境に適したバージョンをインストールしてください。 その後、Xpdfのbinディレクトリをシステム環境変数パスに設定して、ファイルシステムの任意の場所からアクセスできるようにします。

PDFビューアプロジェクトの作成

  1. Code::Blocksを開く: コンピュータでCode::Blocks IDEを起動します。
  2. 新しいプロジェクトの作成: 上部メニューの「ファイル」をクリックし、ドロップダウンメニューから「新規」を選択します。 次に、サブメニューから「プロジェクト」をクリックします。
  3. プロジェクトタイプの選択: 「テンプレートから新規」ウィンドウで「コンソールアプリケーション」を選択し、「Go」をクリックします。 次に、「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関数で、pdfPathoutputFilePathの2つの文字列を宣言します。 pdfPathは入力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ファイルを開きます。 その後、システム関数を呼び出してそのコマンドを実行し、戻り値を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が0以外の場合はエラーを示し、エラーメッセージを表示します。

抽出されたテキストを読み取って表示

// 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++

上記のサンプルコードでは、pdftotextによって生成されたテキストファイルであるoutputFileを開き、その内容を1行ずつ読み込み、textContent文字列に格納します。 最終的にファイルを閉じて、抽出されたテキストコンテンツをコンソールに表示します。

出力ファイルを削除

編集可能な出力テキストファイルが不要な場合やディスクスペースを解放したい場合、プログラムの最後にmain関数を終了する前に、次のコマンドを使用してそれを削除します:

// 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#ライブラリは、C#アプリケーション内でPDFファイルを簡単に表示できる強力な.NET C# PDFライブラリです。 Chromiumウェブブラウザエンジンを活用することで、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では、「ツール」 > 「NuGetパッケージマネージャー」 > 「ソリューションのNuGetパッケージの管理」に行きます。 または、ソリューションエクスプローラーをクリックし、「ソリューションのNuGetパッケージの管理」を選択します。
  4. IronPDFを検索: 「NuGetパッケージマネージャー」ウィンドウで「参照」タブをクリックし、検索バーで「IronPDF」を検索します。 または、NuGet IronPDFパッケージを訪れて最新バージョンの「IronPDF」を直接ダウンロードします。
  5. IronPDFパッケージを選択: 「IronPDF」パッケージを見つけてプロジェクト用に選択します。
  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(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。