0
0

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.

C#とVB.NETでPDF から画像を抽出する

Last updated at Posted at 2023-07-12

PDFから画像を抽出することは、PDF文書内の画像リソースを効果的に管理し活用するための重要な手段です。これらの画像は、変換や編集、再利用、印刷など、さまざまな目的に活用できます。この記事では、Javaプログラムを使用してPDFから画像を抽出する方法について詳しく解説します。

プログラム環境

DLLファイルのインポート

  • Visual Studioを開いて新しいプロジェクトを作成します。
  • 「Solution Explorer」で「References」を右クリックします。
  • 「NuGet Manage Packages」を選択します。
  • Free Spire.PDF for .NETを検索してインストールします。

または、このリンクから直接ダウンロードすることもできます。

  • Visual Studioを開いて新しいプロジェクトを作成します。
  • 「Solution Explorer」で「References」を右クリックします。
  • 「Add Reference」を選択します。
  • 「Browse」をクリックします。
  • DLLを検索してインストールしてプロジェクトにインポートします。

コード

C#:

using Spire.Pdf;
using System.Drawing;

namespace ExtractImages
{
    class Program
    {
        static void Main(string[] args)
        {
            //PdfDocumentインスタンスを作成する
            PdfDocument pdf = new PdfDocument();

            //PDF をロード
            pdf.LoadFromFile("sample.pdf");

            int i = 1;
            //すべてのページをループする
            foreach (PdfPageBase page in pdf.Pages)
            {
                //各ページから画像を抽出し、指定したパスに保存する
                foreach (Image image in page.ExtractImages())
                {
                    image.Save(@"C:/Users/Administrator/Desktop/Images/" + "image" + i + ".png", System.Drawing.Imaging.ImageFormat.Png);
                    i++;
                }
            }
        }
    }
}

VB.net

Imports Spire.Pdf

Namespace ExtractImages
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())

            'PdfDocumentインスタンスを作成する
            Dim pdf As PdfDocument = New PdfDocument()

            'PDF をロード
            pdf.LoadFromFile("sample.pdf")
            Dim i = 1

            'すべてのページをループする
            For Each page As PdfPageBase In pdf.Pages

                '各ページから画像を抽出し、指定したパスに保存する
                For Each image As Image In page.ExtractImages()
                    image.Save("C:/Users/Administrator/Desktop/Images/" & "image" & i & ".png", Drawing.Imaging.ImageFormat.Png)
                    i += 1
                Next
            Next
        End Sub
    End Class
End Namespace

説明

  1. Spire.PdfおよびSystem.Drawingの名前空間をインポートします。
  2. PdfDocumentクラスのインスタンスを作成します。
  3. LoadFromFileメソッドを使用して、PDFファイルを読み込みます。
  4. ページごとに画像を抽出し、指定したパスに保存します。
  5. 画像はPNG形式で保存されます。
  6. 最後に、それぞれの画像にユニークな名前を付けるために、カウンター変数iを使用します。

効果イメージ

image.png
上記の方法を参照して、このライブラリを通じて PDFを圧縮し、PDFに画像の透かしテキストの透かしを挿入することもできます。

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?