0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python プログラムで PDF から画像を抽出する

Posted at

はじめに

時折、私たちは画像が含まれたPDF文書を受け取ることがあります。その中の画像をさらに操作したい場合、どうすればよいでしょうか?画像を抽出してフォルダに保存することは、良い選択肢です。少量の文書を処理する場合は、Adobe Acrobatのようなツールを使用して抽出することができます。しかし、大量の処理が必要な場合は、プログラミングを使用して迅速に抽出することをおすすめします。以下は、Pythonコードを例にした方法の紹介です。

ライブラリ

この PDF ライブラリは、Python プラットフォームでの画像抽出をサポートしています。
テキストを抽出したい場合は、この記事も参照してください。
Python: Extract Text from a PDF Document

事前準備

  • まず、Python をダウンロードしてインストールします。
  • Visual Studio Codeで「Extensions」をクリックし、「Python」を検索してインストールします。
  • 「Explorer」-「NO FOLRDER OPENED」-「Open Folder」
  • フォルダーを作成して、それに「.py」 ファイルを追加します。
  • 「Terminal」-「New Terminal」
  • 次のコマンドを入力して、Spire.PDF for Python と plum-dispatch v1.7.4 をインストールします。
pip install Spire.PDF

サンプルコード

まず、使用する必要があるライブラリをインポートします。

from spire.pdf import *
from spire.pdf.common import *

新しい PDF ドキュメントを作成します。

#PdfDocument クラスのインスタンスを作成する
pdf = PdfDocument()

画像を抽出する必要がある PDF ドキュメントをロードします。

#PDFドキュメントをロードする
pdf.LoadFromFile("C:/Users/Administrator/Desktop/Sample.pdf")

画像を保存するリストを作成します。

#画像を保存するリストを作成する
images = []

ドキュメント内の各ページをループし、各ページから画像を抽出してリストに保存します。

#ドキュメント内のページをループする
for i in range(pdf.Pages.Count):
    # Get a page
    page = pdf.Pages.get_Item(i)
    # Extract the images from the page and store them in the created list
    for img in page.ExtractImages():
        images.append(img)

リスト内の画像を PNG ファイルとして保存します。

#リスト内の画像を PNG として保存する
i = 0
for image in images:
    i += 1
    image.Save("C:/Users/Administrator/Desktop/Images/Image-{0:d}.png".format(i), ImageFormat.get_Png())
pdf.Close() 

スクリーンショット

image.png

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?