SelectPdf for .NET 10 - Extract Images from PDF - C# / .NET 10 Sample

This sample shows how to use SelectPdf Library for .NET to extract the images of a PDF document. List Images shows every image with the page it is on and its size; Download Images returns them all in a zip file, in the format chosen below. Only raster images are extracted - text and vector graphics are not images.

The sample uses the following (existing) test PDF, or a PDF you upload:
Test PDF document

PDF document (optional):

Image format:


Password (for a protected PDF):


Sample code · C#
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using SelectPdf.Universal;
using SkiaSharp;

namespace SelectPdf.Samples.Pages
{
    public class ExtractPdfImagesModel : PageModel
    {
        public void OnGet()
        {
            DdlImageFormat = "Png";
        }

        // An uploaded PDF document, or nothing - the shipped files/doc.pdf is used then.
        [BindProperty]
        public IFormFile FilePdf { get; set; }

        [BindProperty]
        public string TxtPassword { get; set; }

        [BindProperty]
        public string DdlImageFormat { get; set; } = "Png";

        public List<SelectListItem> ImageFormats { get; } = new List<SelectListItem>
        {
            new SelectListItem { Value = "Png", Text = "PNG" },
            new SelectListItem { Value = "Jpeg", Text = "JPEG" },
            new SelectListItem { Value = "Bmp", Text = "BMP" },
        };

        // One row of the list shown on the page.
        public class ImageInfo
        {
            public int Number { get; set; }
            public int Page { get; set; }
            public int Width { get; set; }
            public int Height { get; set; }
            public string Format { get; set; }
            public int Bytes { get; set; }
        }

        // The images found, shown on the page.
        public List<ImageInfo> Images { get; } = new List<ImageInfo>();

        // List: show every image of the document, page by page.
        public IActionResult OnPostList()
        {
            try
            {
                foreach (ExtractedImage image in Extract())
                {
                    // read the image size in pixels from the encoded bytes
                    int width = 0, height = 0;
                    using (SKCodec codec = SKCodec.Create(new MemoryStream(image.Bytes)))
                    {
                        if (codec != null)
                        {
                            width = codec.Info.Width;
                            height = codec.Info.Height;
                        }
                    }

                    Images.Add(new ImageInfo
                    {
                        Number = Images.Count + 1,
                        Page = image.Page,
                        Width = width,
                        Height = height,
                        Format = image.Format.ToString().ToUpperInvariant(),
                        Bytes = image.Bytes.Length
                    });
                }
                ViewData["Message"] = "Images found: " + Images.Count;
            }
            catch (Exception ex)
            {
                ViewData["Message"] = "An error occurred: " + ex.Message;
            }
            return Page();
        }

        // Download: return every image of the document in a zip file.
        public IActionResult OnPostDownload()
        {
            try
            {
                List<ExtractedImage> images = Extract();
                if (images.Count == 0)
                {
                    ViewData["Message"] = "The document has no images.";
                    return Page();
                }

                byte[] zip;
                using (var output = new MemoryStream())
                {
                    using (var archive = new ZipArchive(output, ZipArchiveMode.Create, true))
                    {
                        foreach (ExtractedImage image in images)
                        {
                            // named page number + "-" + the image's number on that page
                            string name = string.Format("image-{0}-{1}.{2}", image.Page, image.IndexOnPage,
                                image.Format.ToString().ToLowerInvariant());
                            ZipArchiveEntry entry = archive.CreateEntry(name);
                            using (Stream stream = entry.Open())
                                stream.Write(image.Bytes, 0, image.Bytes.Length);
                        }
                    }
                    zip = output.ToArray();
                }

                // return the zip file
                FileResult fileResult = new FileContentResult(zip, "application/zip");
                fileResult.FileDownloadName = "Images.zip";
                return fileResult;
            }
            catch (Exception ex)
            {
                ViewData["Message"] = "An error occurred: " + ex.Message;
                return Page();
            }
        }

        private class ExtractedImage
        {
            public int Page;
            public int IndexOnPage;
            public PdfImageFormat Format;
            public byte[] Bytes;
        }

        // Extracts the images one page at a time, so each image is known with its page.
        private List<ExtractedImage> Extract()
        {
            byte[] source;
            if (FilePdf != null && FilePdf.Length > 0)
            {
                using (var uploaded = new MemoryStream())
                {
                    FilePdf.CopyTo(uploaded);
                    source = uploaded.ToArray();
                }
            }
            else
            {
                source = System.IO.File.ReadAllBytes(Path.Combine(Startup.ServerPath, "wwwroot", "files", "doc.pdf"));
            }

            var result = new List<ExtractedImage>();
            using (PdfImageExtractor extractor = new PdfImageExtractor())
            {
                // load the pdf document
                if (string.IsNullOrEmpty(TxtPassword))
                    extractor.Load(source);
                else
                    extractor.Load(source, TxtPassword);

                // the format the images are returned in
                extractor.ImagesFormat = SampleForm.ParseEnum(DdlImageFormat, PdfImageFormat.Png);

                // extract the images of each page
                int pageCount = extractor.GetPageCount();
                for (int page = 1; page <= pageCount; page++)
                {
                    extractor.StartPageNumber = page;
                    extractor.EndPageNumber = page;
                    byte[][] images = extractor.ExtractImages();
                    for (int i = 0; i < images.Length; i++)
                    {
                        result.Add(new ExtractedImage
                        {
                            Page = page,
                            IndexOnPage = i + 1,
                            Format = extractor.ImagesFormat,
                            Bytes = images[i]
                        });
                    }
                }
            }
            return result;
        }
    }
}