RemoveImageLocation.cs
//
// This code is part of Document Solutions for PDF demos.
// Copyright (c) MESCIUS inc. All rights reserved.
//
using System;
using System.IO;
using System.Drawing;
using System.Text;
using GrapeCity.Documents.Pdf;
using GrapeCity.Documents.Text;
using GrapeCity.Documents.Drawing;
using System.Linq;

namespace DsPdfWeb.Demos
{
    // This demo shows how to remove some instances (locations) of an image
    // from a PDF using the GcPdfDocument.RemoveImages() method.
    public class RemoveImageLocation
    {
        public int CreatePDF(Stream stream)
        {
            using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "ImageTransparency.pdf"));
            var doc = new GcPdfDocument();
            doc.Load(fs);
            // Get the list of images in the document:            
            var imageInfos = doc.GetImages();
            // For each image with multiple locations, remove the leftmost location:
            foreach (var ii in imageInfos)
            {
                if (ii.Locations.Count > 1)
                {
                    int iLeft = -1;
                    for (int i = 0; i < ii.Locations.Count; i++)
                    {
                        if (iLeft == -1 || ii.Locations[i].PageBounds.ToRect().Left < ii.Locations[iLeft].PageBounds.ToRect().Left)
                            iLeft = i;
                    }
                    // Remove the locations we want to keep:
                    for (int i = ii.Locations.Count - 1; i >= 0; i--)
                        if (i != iLeft)
                            ii.Locations.RemoveAt(i);
                    // Remove the locations that are left:
                    doc.RemoveImages([ii]);
                }
            }
            // Done:
            doc.Save(stream);
            return doc.Pages.Count;
        }
    }
}