Articles in this section
Category / Section

How to reorder PDF pages using ListView?

4 mins read

You can rearrange the PDF pages by extracting the pages as images using PDF viewer, loading them into a ListView, and dragging to the position you need. The rearranged PDF can be saved using the PdfLoadedDocument.

 

Include a ListView to load the pages and a button to save the PDF. The CanReorderItems, CanDragItems, and AllowDrop properties of the ListView must be set to “True”. Add a Grid that contains an Image control to the ListView’s ItemTemplate. The pages are rendered on these Image controls.

 

XAML

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
 
        <ListView x:Name="pdfRearranger" Width="300" CanReorderItems="True" CanDragItems="True" AllowDrop="True" ItemsSource="{x:Bind ViewModel.PageList}" ShowsScrollingPlaceholders="False">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Grid HorizontalAlignment="Center">
                        <Image Source="{Binding PageImageSource}"/>
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
 
        <Button x:Name="saveButton" Click="saveButton_Click" Content="Save" />
 
    </Grid>

 

Add a new class named CustomImage to the project. It must have two properties of type ImageSource and int with the names PageImageSource and PageNumber respectively. The Source property of the Image control in the ListView’s ItemTemplate can bound to the PageImageSource property. The other integer property helps to identify the original page number associated with the image.

 

 

C#

public class CustomImage
    {
        private Image pageImage;
        private int pageNumber;
        public CustomImage(int pageNum, Image image)
        {
            pageNumber = pageNum;
            pageImage = image;
        }
 
        public ImageSource PageImageSource
        {
            get
            {
                return pageImage.Source;
            }
        }
 
        public int PageNumber
        {
            get { return pageNumber; }
        }
    }

 

Add a ViewModel class to the project with the name “RearrangePagesViewModel”. Define a property of type ObservableCollection<CustomImage> in this class. The ItemsSource property of the ListView must bound to this property as shown in the previous XAML code. 

Implement the logic of exporting the PDF pages as images using PDF viewer and adding them to the PageList in the constructor of the RearrangePagesViewModel class. Define an asynchronous method that implements this logic and call the method from the constructor, as the keyword async cannot be used with the constructor.

 

C#

public class RearrangePagesViewModel
    {
        ObservableCollection<CustomImage> pageList;
 
        public ObservableCollection<CustomImage> PageList
        {
            get
            {
                return pageList;
            }
        }
        public RearrangePagesViewModel()
        {
            pageList = new ObservableCollection<CustomImage>();
            //Obtain the stream of the PDF from the Assets folder
            Stream stream1 = typeof(MainPage).GetTypeInfo().Assembly.GetManifestResourceStream("RearrangePagesDemo.Assets.HTTP_Succinctly.pdf");
 
            SfPdfViewerControl pdfViewerControl = new SfPdfViewerControl();
 
            //Load the stream to PDF viewer
            pdfViewerControl.LoadDocument(stream1);
 
            for (int i = 0; i < pdfViewerControl.PageCount; i++)
            {
                //Get the page with the current index in image form
                Image image = pdfViewerControl.GetPage(i);
 
                //Add the page image to the observable collection
                pageList.Add(new CustomImage(i, image));
            }
        }
    }

 

In the main page of the project, get the stream of the PDF to be loaded and create a PdfLoadedDocument instance and in the constructor, initialize the RearrangePagesViewModel class. Define and wire a handler method for the Click event  of the save button as shown in the XAML code. In this method, implement the logic to save the PDF with the current page order as displayed in the ListView. The file is saved to the LocalFolder of the application.

 

C#

public sealed partial class MainPage : Page
    {
        
        List<int> pageIndexOrder = new List<int>();
        PdfLoadedDocument pdfLoadedDocument;
        RearrangePagesViewModel ViewModel; 
        public MainPage()
        {
            this.InitializeComponent();
            Stream stream = typeof(MainPage).GetTypeInfo().Assembly.GetManifestResourceStream("RearrangePagesDemo.Assets.HTTP_Succinctly.pdf");
 
            //The pdfLoadedDocument is used to rearrange the pages in the PDF file while saving
            pdfLoadedDocument = new PdfLoadedDocument(stream);
            ViewModel = new RearrangePagesViewModel();
        }
 
        private async void saveButton_Click(object sender, RoutedEventArgs e)
        {
            Stream savedStream = new MemoryStream();
            int[] orderArray = new int[pdfLoadedDocument.Pages.Count];
 
            //Get the page number order of the pages in the ListView
 
            for(int i = 0; i < ViewModel.PageList.Count; i++)
            {
                orderArray[i] = ViewModel.PageList[i].PageNumber;
            }
 
            //Rearrange the pages of the PDF by the order in which the pages are arranged in the ListView now
            pdfLoadedDocument.Pages.ReArrange(orderArray);
            pdfLoadedDocument.Save(savedStream);
 
            //Save the stream to a file in the LocalFolder
            StorageFolder folder = ApplicationData.Current.LocalFolder;
            StorageFile file = await folder.CreateFileAsync("SavedDocument.pdf", CreationCollisionOption.ReplaceExisting);
            if (file != null)
            {
                Windows.Storage.Streams.IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite);
                Stream st = fileStream.AsStreamForWrite();
                st.SetLength(0);
                st.Write((savedStream as MemoryStream).ToArray(), 0, (int)savedStream.Length);
                st.Flush();
                st.Dispose();
                fileStream.Dispose();
            }
        }
    }

 

Sample link:

https://www.syncfusion.com/downloads/support/directtrac/general/ze/RearrangePagesDemo-966812100

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied